diff --git a/dist/0.6531d7c910f326b2774d.js.map b/dist/0.6531d7c910f326b2774d.js.map deleted file mode 100644 index 6c5020cf..00000000 --- a/dist/0.6531d7c910f326b2774d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///./src/hooks/useLang.ts","webpack:///./src/components/ui/ListItem.tsx","webpack:///./src/hooks/useIntersectionObserver.ts","webpack:///./src/hooks/useMedia.ts","webpack:///./src/components/common/PrivateChatInfo.tsx","webpack:///./src/components/ui/Modal.tsx","webpack:///./src/util/trapFocus.ts","webpack:///./src/components/ui/Transition.tsx","webpack:///./src/components/common/Avatar.tsx","webpack:///./src/components/ui/InfiniteScroll.tsx","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/hooks/useTransitionForMedia.ts","webpack:///./src/components/common/helpers/mediaDimensions.ts","webpack:///./src/components/common/AnimatedSticker.tsx","webpack:///./src/components/ui/ConfirmDialog.tsx","webpack:///./src/components/common/NothingFound.tsx","webpack:///./src/components/right/hooks/useAsyncRendering.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/hooks/useMediaWithDownloadProgress.ts","webpack:///./src/components/ui/ProgressSpinner.tsx","webpack:///./src/components/ui/Portal.ts","webpack:///./src/components/common/GroupChatInfo.tsx","webpack:///./src/util/fastSmoothScroll.ts","webpack:///./src/components/ui/Radio.tsx","webpack:///./src/components/ui/RadioGroup.tsx","webpack:///./src/hooks/useInfiniteScroll.ts","webpack:///./src/components/common/AnimatedEmoji.tsx","webpack:///./src/util/captureEvents.ts","webpack:///./src/components/common/VerifiedIcon.tsx","webpack:///./src/hooks/useBuffering.ts","webpack:///./src/util/focusEditableElement.ts","webpack:///./src/components/middle/composer/helpers/parseMessageInput.ts","webpack:///./src/components/middle/composer/DropTarget.tsx","webpack:///./src/components/middle/composer/DropArea.tsx","webpack:///./src/hooks/useBackgroundMode.ts","webpack:///./src/components/common/PickerSelectedItem.tsx","webpack:///./src/hooks/useHorizontalScroll.ts","webpack:///./src/hooks/useEnsureMessage.ts","webpack:///./src/hooks/useContextMenuHandlers.ts","webpack:///./src/util/cycleRestrict.ts","webpack:///./src/util/safePlay.ts","webpack:///./src/components/common/helpers/renderMessageText.tsx","webpack:///./src/hooks/useBlur.ts","webpack:///./src/hooks/useVideoCleanup.ts","webpack:///./src/util/clipboard.ts","webpack:///./src/components/ui/SearchInput.tsx","webpack:///./src/util/fastSmoothScrollHorizontal.ts","webpack:///./src/util/resetScroll.ts","webpack:///./src/util/trimText.ts","webpack:///./src/components/common/TypingStatus.tsx","webpack:///./src/components/common/DeleteChatModal.tsx","webpack:///./src/util/patchSafariProgressiveAudio.ts","webpack:///./src/hooks/useLayoutEffectWithPrevDeps.ts","webpack:///./src/components/common/Document.tsx","webpack:///./src/components/common/StickerSetModal.async.tsx","webpack:///./src/components/middle/composer/TextFormatter.tsx","webpack:///./src/components/common/Media.tsx","webpack:///./src/components/common/Audio.tsx","webpack:///./src/util/waveform.ts","webpack:///./src/components/common/helpers/waveform.ts","webpack:///./src/components/ui/Tab.tsx","webpack:///./src/components/ui/TabList.tsx","webpack:///./src/util/getReadableErrorText.ts","webpack:///./src/hooks/useChatContextActions.ts","webpack:///./src/components/common/LastMessageMeta.tsx","webpack:///./src/components/common/MessageOutgoingStatus.tsx","webpack:///./src/hooks/useContextMenuPosition.ts","webpack:///./src/components/ui/ShowTransition.tsx","webpack:///./src/hooks/useAudioPlayer.ts","webpack:///./src/util/audioPlayer.ts","webpack:///./src/util/download.ts","webpack:///./src/components/common/File.tsx","webpack:///./src/lib/fastBlur.js","webpack:///./src/components/ui/Notification.tsx","webpack:///./src/components/middle/composer/helpers/selection.ts","webpack:///./src/components/middle/composer/MessageInput.tsx","webpack:///./src/hooks/useBlurSync.ts","webpack:///./src/components/common/WebLink.tsx","webpack:///./src/components/left/main/hooks/useChatAnimationType.ts","webpack:///./src/components/left/main/Badge.tsx","webpack:///./src/components/left/main/Chat.tsx","webpack:///./src/components/left/main/ChatList.tsx","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/components/middle/composer/hooks/useMentionMenu.ts","webpack:///./src/components/middle/composer/helpers/searchUserName.ts"],"names":["forceUpdate","useForceUpdate","useOnChange","langProvider","ListItem","props","ref","icon","className","style","children","disabled","ripple","narrow","inactive","focus","destructive","multiline","contextActions","onClick","containerRef","useRef","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","getTriggerElement","useCallback","current","getRootElement","closest","getMenuElement","querySelector","positionX","positionY","menuStyle","useContextMenuPosition","handleClick","e","handleMouseDown","IS_TOUCH_ENV","button","fullClassName","buildClassName","role","tabIndex","undefined","onMouseDown","onContextMenu","isOpen","autoClose","onClose","onCloseAnimationEnd","map","action","key","title","handler","useIntersectionObserver","rootRef","throttleMs","debounceMs","shouldSkipFirst","margin","threshold","isDisabled","rootCallback","controllerRef","rootCallbackRef","isFrozenRef","onUnfreezeRef","freeze","unfreeze","useHeavyAnimationCheck","useEffect","observer","disconnect","callbacks","clear","observe","target","targetCallback","Map","entriesAccumulator","observerCallbackSync","entries","Array","from","values","forEach","entry","callback","get","scheduler","throttle","debounce","observerCallback","IntersectionObserver","set","root","rootMargin","initController","controller","delete","unobserve","useOnIntersect","targetRef","useIsIntersecting","isIntersecting","setIsIntersecting","useState","mediaHash","noLoad","mediaFormat","ApiMediaFormat","BlobUrl","cacheBuster","delay","mediaData","mediaLoader","startedAt","Date","now","then","spentTime","setTimeout","memo","withGlobal","global","userId","forceShowSelf","lastSyncTime","user","selectUser","isSavedMessages","isSelf","areMessagesLoaded","Boolean","selectChatMessages","setGlobal","actions","pick","typingStatus","avatarSize","status","withMediaViewer","withUsername","withFullInfo","withUpdatingStatus","noStatusOrTyping","loadFullUser","openMediaViewer","id","fullName","getUserFullName","handleAvatarViewerOpen","hasPhoto","stopPropagation","avatarOwnerId","origin","MediaViewerOrigin","ProfileAvatar","MiddleHeaderAvatar","lang","useLang","size","renderText","isVerified","isUserOnline","username","getUserStatus","Modal","header","hasCloseButton","noBackdrop","onEnter","shouldRender","transitionClassNames","useShowTransition","modalRef","captureKeyboardListeners","onEsc","element","handleKeyDown","preventDefault","focusableElements","querySelectorAll","length","currentFocusedIndex","findIndex","em","isSameNode","document","activeElement","newFocusedIndex","shiftKey","addEventListener","removeEventListener","trapFocus","useEffectWithPrevDeps","prevIsOpen","body","classList","toggle","dispatchHeavyAnimationEvent","remove","Portal","Button","round","color","ariaLabel","ANIMATION_DURATION","slide","fade","IS_MOBILE_SCREEN","reveal","CLEANED_UP","Symbol","animationLevel","settings","byKey","activeKey","name","direction","renderCount","shouldRestoreHeight","shouldCleanup","onStart","onStop","rendersRef","prevActiveKey","usePrevious","activateTimeoutRef","activeKeyChanged","useLayoutEffect","cleanup","container","childElements","add","childNodes","clearTimeout","isBackwards","keys","Object","Number","prevActiveIndex","indexOf","activeIndex","node","i","HTMLElement","width","offsetWidth","scrollBy","left","behavior","ANIMATION_END_DELAY","requestAnimationFrame","window","scrollLeft","height","clientHeight","renders","contents","fill","render","chat","text","withOnlineStatus","isDeleted","isDeletedUser","imageHash","getChatAvatarHash","dataUri","useMedia","DataUri","shouldRenderFullMedia","useTransitionForMedia","content","src","alt","decoding","userFullName","getFirstLetters","getChatTitle","isChatPrivate","isOnline","getUserColorKey","senderId","data-test-sender-id","IS_TEST","InfiniteScroll","onLoadMore","onScroll","items","itemSelector","preloadBackwards","sensitiveArea","noScrollRestore","noFastList","stateRef","loadMoreBackwards","loadMoreForwards","useMemo","LoadMoreDirection","Backwards","Forwards","scrollHeight","state","listItemElements","newScrollTop","currentAnchor","includes","scrollTop","getBoundingClientRect","top","currentAnchorTop","nextAnchor","offsetParent","resetScroll","isScrollTopJustUpdated","handleScroll","listLength","offsetHeight","isNearTop","offsetTop","isNearBottom","isUpdated","nextAnchorTop","newAnchorTop","teactFastList","cb","dependencies","prevDeps","some","d","SPEED","fast","slow","speed","noAnimate","isMediaLoaded","willAnimate","shouldRenderThumb","setShouldRenderThumb","MEDIA_VIEWER_MEDIA_QUERY","REM","parseInt","getComputedStyle","documentElement","fontSize","ROUND_VIDEO_DIMENSIONS","AVATAR_FULL_DIMENSIONS","DEFAULT_MEDIA_DIMENSIONS","cachedMaxWidth","getAvailableWidth","fromOwnMessage","isForwarded","isWebPagePhoto","extraPaddingRem","regularMaxWidth","Math","min","floor","innerWidth","getMaxMessageWidthRem","calculateDimensionsForMessageMedia","isGif","aspectRatio","calculateDimensions","getAvailableHeight","getMediaViewerAvailableDimensions","withFooter","isVideo","mql","matchMedia","windowWidth","windowHeight","windowSize","occupiedHeightRem","matches","calculateInlineImageDimensions","photo","getPhotoInlineDimensions","calculateVideoDimensions","video","getVideoDimensions","getPictogramDimensions","getDocumentThumbnailDimensions","smaller","getStickerDimensions","sticker","baseWidth","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_INLINE_DESKTOP_FACTOR","calculatedHeight","calculateMediaViewerDimensions","availableWidth","availableHeight","mediaWidth","mediaHeight","calculatedWidth","lottiePromise","RLottie","async","ensureLottie","default","animationData","play","playSegment","noLoop","quality","isLowPriority","onLoad","animation","setAnimation","wasPlaying","isFrozen","playRef","playSegmentRef","exec","newAnimation","setSpeed","fastRaf","destroy","playAnimation","shouldRestart","goToAndPlay","pauseAnimation","pause","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","useBackgroundMode","IS_IOS","textParts","confirmLabel","confirmHandler","confirmIsDestructive","isButtonsInOneRow","split","textPart","isText","useAsyncRendering","shouldRenderRef","timeoutRef","Link","href","isStreaming","Stream","IS_PROGRESSIVE_SUPPORTED","Progressive","downloadProgress","setDownloadProgress","startedAtRef","handleProgress","progress","RADIUSES","s","m","l","xl","square","transparent","noCross","radius","circleRadius","STROKE_WIDTH","borderRadius","circumference","PI","svg","firstElementChild","strokeDashOffset","max","setAttribute","toString","innerHTML","containerId","elementRef","createElement","appendChild","TeactDOM","removeChild","chatId","selectChat","onlineCount","selectChatOnlineCount","withChatType","loadFullChat","isSuperGroup","isChatSuperGroup","isMin","isRestricted","getChatTypeString","handle","groupStatus","chatTypeString","membersCount","getGroupStatus","onlineStatus","renderStatusOrTyping","isAnimating","fastSmoothScroll","position","maxDistance","forceDirection","forceDuration","forceCurrentContainerHeight","FocusDirection","Static","scrollIntoView","block","offset","Up","Down","elementTop","elementHeight","containerHeight","targetContainerHeight","dataset","normalHeight","path","remainingPath","duration","abs","startAt","animateSingle","t","currentPath","transition","scrollWithJs","isAnimatingScroll","label","subLabel","value","checked","hidden","isLoading","onChange","type","Spinner","options","selected","loadingOption","handleChange","event","currentTarget","option","getViewportSlice","sourceIds","offsetId","listSlice","index","indexForDirection","to","newViewportIds","slice","areSomeLocal","areAllLocal","listIds","forceFullPreload","lastParamsRef","viewportIdsRef","prevListIds","prevIsDisabled","areSortedArraysEqual","viewportIds","getMore","AnimatedEmoji","isInline","observeIntersection","isAnimationLoaded","markAnimationLoaded","useFlag","localMediaHash","previewBlobUrl","Lottie","playKey","setPlayKey","String","random","STICKER_SIZE_TWO_FA","SwipeDirection","captureEvents","captureEvent","hasMoved","onCapture","excludedClosestSelector","onMove","onRelease","pageX","touches","pageY","withCursor","dragOffsetX","dragOffsetY","onDrag","onSwipe","xAbs","yAbs","Left","Right","processSwipe","passive","VerifiedIcon","noInitiallyBuffered","isBuffered","setIsBuffered","bufferedProgress","setBufferedProgress","setIsBufferedDebounced","handleBuffering","media","isSafariPatchInProgress","buffered","end","readyState","currentTime","bufferingHandlers","onLoadedData","onPlaying","onLoadStart","onPause","onTimeUpdate","onProgress","checkBuffering","focusEditableElement","force","selection","getSelection","range","createRange","lastChild","nodeValue","setStart","removeAllRanges","addRange","ENTITY_CLASS_BY_NODE_NAME","B","ApiMessageEntityTypes","Bold","STRONG","I","Italic","EM","U","Underline","S","Strike","STRIKE","DEL","CODE","Code","PRE","Pre","BLOCKQUOTE","Blockquote","parseMessageInput","html","fragment","parsedHtml","IS_EMOJI_SUPPORTED","replace","parseMarkdown","innerText","trim","textIndex","recursionDeepness","entities","addEntity","entity","rawText","nodeName","anchor","entityType","MentionName","startsWith","Email","Phone","textContent","TextUrl","Url","getEntityTypeFromNode","rawIndex","substring","url","getEntityDataFromNode","push","hasChildNodes","isQuick","onFileSelect","isHovered","markHovered","unmarkHovered","onDrop","onDragEnter","onDragLeave","relatedTarget","toTarget","DropAreaState","withQuick","onHide","hideTimeoutRef","prevWithQuick","captureEscKeyListener","handleFilesDrop","dataTransfer","dt","files","handleQuickFilesDrop","handleDragLeave","fromTarget","onDragOver","onBlur","onFocus","hasFocus","chatOrUserId","isMinimized","canClose","clickArg","iconElement","titleText","getUserFirstOrLastName","deltaX","deltaY","messageId","message","replyOriginForId","loadMessage","getDispatch","loadMessageThrottled","throttled","contextMenuCounter","isMenuDisabled","setIsContextMenuOpen","setContextMenuPosition","x","clientX","y","clientY","timer","clearLongPressTimer","startLongPressTimer","contains","originalEvent","cancelClickOnce","stopImmediatePropagation","emulateContextMenuEvent","cycleRestrict","mediaEl","catch","err","DEBUG","console","warn","renderMessageText","highlight","shouldRenderHqEmoji","formattedText","getMessageText","renderTextWithEntities","organizeEntities","organizedEntityIndexes","Set","organizedEntities","has","organizedEntity","organizeEntity","organizedIndexes","nestedEntities","filter","organizedIndex","shouldRenderAsHtml","renderMessagePart","result","deleteLineBreakAfterPre","organizedEntites","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","join","getLinkUrl","processEntityAsHtml","entityText","BotCommand","handleBotCommandClick","Hashtag","Cashtag","handleHashtagClick","rel","Mention","processEntity","isArray","textAfter","arrayIndex","c","emojiFilter","sendBotCommand","command","setLocalTextSearchQuery","query","searchTextMessagesLocal","cache","useBlur","blurredRef","img","Image","onload","canvas","imgToCanvas","fastBlur","getContext","blurredDataUri","toDataURL","useVideoCleanup","videoRef","videoEl","load","CLIPBOARD_ITEM_SUPPORTED","navigator","clipboard","ClipboardItem","textCopyEl","copyTextToClipboard","str","rangeToRestore","rangeCount","getRangeAt","select","execCommand","copyImageToClipboard","imageUrl","ctx","imageEl","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","error","inputId","focused","placeholder","onReset","inputRef","isInputFocused","markInputFocused","unmarkInputFocused","blur","containerWidth","scrollWidth","animate","scrollTo","overflow","trimText","typingUser","typingUserName","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","canDeleteForAll","contactName","getPrivateChatUserId","isChannel","isChatChannel","isBasicGroup","isChatBasicGroup","chatTitle","leaveChannel","deleteHistory","deleteChannel","handleDeleteMessageForAll","maxId","lastMessage","shouldDeleteForAll","handleDeleteChat","isCreator","patchSafariProgressiveAudio","audioEl","patchedForSafari","patchForSafariInProgress","paused","once","uploadProgress","withDate","datetime","sender","isSelected","isSelectable","onCancelUpload","onDateClick","extension","getDocumentExtension","fileName","timestamp","isDownloadAllowed","setIsDownloadAllowed","useMediaWithDownloadProgress","getMessageMediaHash","isUploading","isTransferring","transferProgress","getMediaTransferState","hasPreview","getDocumentHasPreview","thumbDataUri","getMessageMediaThumbDataUri","localBlobUrl","previewData","isAllowed","handleDateClick","download","thumbnailDataUri","StickerSetModalAsync","StickerSetModal","useModuleLoader","Bundles","Extra","TEXT_FORMAT_BY_TAG_NAME","anchorPosition","selectedRange","linkUrlInputRef","isLinkControlOpen","openLinkControl","closeLinkControl","linkUrl","setLinkUrl","isEditingLink","setIsEditingLink","inputClassName","setInputClassName","selectedTextFormats","setSelectedTextFormats","useVirtualBackdrop","selectedFormats","parentElement","commonAncestorContainer","EDITABLE_INPUT_ID","textFormat","tagName","getSelectedText","getSelectedElement","updateInputStyles","input","getFormatButtonClassName","fKey","monospace","strikethrough","handleBoldText","bold","handleItalicText","italic","handleUnderlineText","underline","handleStrikethroughText","replaceWith","handleMonospaceText","handleLinkUrlConfirm","formattedLinkUrl","restoreSelection","KeyK","KeyB","KeyU","KeyI","KeyM","KeyS","code","altKey","ctrlKey","metaKey","linkUrlConfirmClassName","onKeyDown","autoComplete","inputMode","idPrefix","mediaBlobUrl","getMessageVideo","formatMediaDuration","MIN_SPIKES","MAX_SPIKES","renderSeekline","playProgress","handleStartSeek","handleSeek","handleStopSeek","onMouseMove","onMouseUp","theme","senderTitle","renderingFor","date","onPlay","onReadMedia","audio","voice","isMediaUnread","isVoice","isSeeking","isActivated","setIsActivated","shouldDownload","getMessageMediaFormat","useBuffering","playPause","setCurrentTime","useAudioPlayer","getMessageKey","getMediaDuration","isMessageLocal","shouldRenderSpinner","spinnerClassNames","handleButtonClick","seekBar","seekHandlers","isOwn","isOwnMessage","renderedWaveform","waveform","fillColor","fillOwnColor","progressFillColor","progressFillOwnColor","durationFactor","spikesCount","decodedWaveform","encoded5bit","bitsCount","valuesCount","bitsData","byteIndex","bitShift","lastByteIndex","lastBitShift","lastValue","decodeWaveform","Uint8Array","data","spikes","peak","fitCount","newData","springFactor","leftFiller","rightFiller","idx","val","interpolateArray","fillStyle","progressFillStyle","scale","item","globalAlpha","spikeHeight","beginPath","moveTo","arcTo","closePath","roundedRectangle","renderWaveformToDataUri","draggable","renderWaveform","buttonClassNames","showSeekline","contentClassName","ProgressSpinner","getFirstLine","formatPastTimeShort","performer","getSecondLine","formatMediaDateTime","renderAudio","renderVoice","active","badgeCount","isBadgeActive","previousActiveTab","tabRef","tab","indicator","currentIndicator","shiftLeft","offsetLeft","scaleFactor","clientWidth","transform","tabs","activeTab","onSwitchTab","useHorizontalScroll","activeTabElement","newLeft","fastSmoothScrollHorizontal","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","LINK_NOT_MODIFIED","SERVICE_WORKER_DISABLED","CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","reduce","acc","privateChatUser","handleDelete","folderId","isPinned","toggleChatPinned","updateChatMutedState","toggleChatArchived","toggleChatUnread","actionUnreadMark","unreadCount","hasUnreadMark","actionPin","actionMute","isMuted","actionArchive","isChatArchived","getCanDeleteChat","LastMessageMeta","outgoingStatus","Keys","MessageOutgoingStatus","extraPaddingX","extraTopPadding","setPositionX","setPositionY","setStyle","triggerEl","emptyRect","menuEl","rootEl","triggerRect","menuRect","rootRect","ShowTransition","isCustom","prevChildren","fromChildrenRef","trackId","originalDuration","handlers","onInit","shouldPlay","onForcePlay","noPlaylist","setIsPlaying","isPlayingSync","setPlayProgress","register","eventName","proxy","isFinite","prevShouldPlay","prevSrc","audioProxy","tracks","currentTrackId","queue","stopCurrentAudio","currentTrack","Audio","handleEvent","nextTrackId","openAudioPlayer","parseMessageKey","nextTrack","safePlay","Proxy","createAudio","preload","IS_SAFARI","time","shouldRemoveFromQueue","track","h","filename","link","click","shouldSpinnerRender","getColorFromExtension","sizeString","getFileSizeString","mul_table","shg_table","boxBlurCanvasRGB","context","top_x","top_y","iterations","isNaN","imageData","getImageData","pixels","rsum","gsum","bsum","p","p1","p2","yp","yi","yw","wm","hm","rad1","r","g","b","mul_sum","shg_sum","vmin","vmax","putImageData","onDismiss","setIsOpen","timerRef","closeAndDismiss","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","isSelectionInsideInput","selectionRange","parentNode","MAX_INPUT_HEIGHT","currentChatId","threadId","selectCurrentMessageList","messageSendKeyCombo","replyingToId","selectReplyingToId","noTabCapture","isPollModalOpen","payment","isPaymentModalOpen","editableInputId","shouldSetFocus","shouldSupressFocus","onUpdate","onSupressedFocus","onSend","editLastMessage","cloneRef","isContextMenuOpenRef","isTextFormatterOpen","openTextFormatter","closeTextFormatter","textFormatterAnchorPosition","setTextFormatterAnchorPosition","setSelectedRange","useLayoutEffectWithPrevDeps","prevHtml","willSend","clone","currentHeight","newHeight","transitionDuration","log","updateInputHeight","focusInput","handleCloseTextFormatter","empty","clearSelection","checkSelection","selectedText","parseEmojiOnlyString","START_TO_END","selectionRect","inputRect","captureFirstTab","onTab","supressFocus","contentEditable","handleKeyUp","IS_ANDROID","closeContextMenuMouseListener","closeContextMenuKeyListener","handleMouseUp","onTouchCancel","useBlurSync","isChanged","blurredAsync","onMessageClick","linkData","getMessageWebPage","getFirstLinkInMessage","domain","messageText","getMessageSummaryText","siteName","description","handleMessageClick","displayUrl","truncatedDescription","data-initial","ChatAnimationTypes","Badge","isShown","renderContent","unreadMentionsCount","formatIntegerCompact","FolderTypeToListType","replyToMessageId","isOutgoing","lastMessageSender","lastMessageAction","getMessageAction","actionTargetMessage","selectChatMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","privateChatUserId","messageListType","lastMessageOutgoingStatus","selectOutgoingStatus","actionTargetUser","draft","selectDraft","MAIN_THREAD_ID","orderDiff","animationType","openChat","focusLastMessage","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isAction","isActionMessage","useEnsureMessage","mediaThumbnail","getMessageSticker","Opacity","opacity","Move","useChatContextActions","Avatar","TypingStatus","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","blobUrl","renderMessageSummary","renderLastMessageOrTyping","DeleteChatModal","folderType","chats","byId","chatsById","orderedPinnedIds","users","usersById","currentThreadId","listType","chatFolder","selectChatFolder","isInDiscussionThread","noChatsText","loadMoreChats","preloadTopChatMessages","currentListIds","currentPinnedIds","prepareFolderListIds","orderById","orderedIds","newChatArrays","prepareChatList","singleList","pinnedChats","otherChats","newOrderedIds","prevOrderById","orderDiffById","mapValues","order","Infinity","loadMoreOfType","useInfiniteScroll","CHAT_LIST_SLICE","ALL_CHATS_PRELOAD_DISABLED","chatArrays","getAnimationType","movesUp","movesDown","orderDiffIds","numberOfUp","numberOfDown","None","useChatAnimationType","viewportOffset","pinnedOffset","CHAT_HEIGHT_PX","teactOrderKey","getChatOrder","renderChats","Loading","openUserInfo","focusMessage","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","isChat","renderChatContent","renderUserContent","pop","getMessageContent","showQuotes","renderMessageContent","invoice","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","RE_NOT_USERNAME_SEARCH","useMentionMenu","canSuggestMembers","onUpdateHtml","groupChatMembers","currentUserId","markIsOpen","unmarkIsOpen","currentFilter","setCurrentFilter","filteredMembers","setFilteredMembers","getFilteredMembers","usernameLowered","toLowerCase","fullNameLowered","filterLowered","searchWords","searchUserName","usernameFilter","tempEl","lastSymbol","lastWord","test","getUsernameFilter","membersToMention","insertMention","forceFocus","insertedHtml","atIndex","lastIndexOf","messageInput","getElementById","isMentionMenuOpen","mentionFilter","closeMentionMenu","mentionFilteredMembers"],"mappings":"uGAEA,6BAMe,SACb,MAAMA,EAAcC,cAMpB,OAJAC,YAAY,IACHC,IAAyBH,GAC/B,CAACA,IAEGG,M,6BCdT,0EAgLeC,IAzIiBC,IAC9B,MAAM,IACJC,EADI,KAEJC,EAFI,UAGJC,EAHI,MAIJC,EAJI,SAKJC,EALI,SAMJC,EANI,OAOJC,EAPI,OAQJC,EARI,SASJC,EATI,MAUJC,EAVI,YAWJC,EAXI,UAYJC,EAZI,eAaJC,EAbI,QAcJC,GACEd,EAGJ,IAAIe,EAAeC,YAAuB,MACtCf,IACFc,EAAed,GAGjB,MAAM,kBACJgB,EADI,oBACeC,EADf,wBAEJC,EAFI,kBAEqBC,EAFrB,uBAGJC,EAHI,sBAGoBC,GACtBC,YAAuBR,GAAeF,GAEpCW,EAAoBC,YAAY,IAAMV,EAAaW,QAAS,IAE5DC,EAAiBF,YACrB,IAAMV,EAAaW,QAASE,QAAQ,kBACpC,IAGIC,EAAiBJ,YACrB,IAAMV,EAAaW,QAASI,cAAc,kCAC1C,KAGI,UAAEC,EAAF,UAAaC,EAAW5B,MAAO6B,GAAcC,YACjDhB,EACAM,EACAG,EACAE,GAGIM,EAAcV,YAAaW,KAC3B9B,GAAaQ,GAGjBA,EAAQsB,IACP,CAAC9B,EAAUQ,IAERuB,EAAkBZ,YAAaW,IAC/B3B,GAAY6B,OAGZzB,GAAgC,IAAbuB,EAAEG,QAAiBzB,GACxCK,EAAwBiB,GAET,IAAbA,EAAEG,SACCzB,EAGHqB,EAAYC,GAFZhB,EAAkBgB,MAKrB,CAAC3B,EAAUI,EAAgBC,EAASK,EAAyBC,EAAmBe,IAE7EK,EAAgBC,YACpB,wB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KACxCC,IAAaA,EAASj0B,WAAW,KAErC,OAGF,OAAOi0B,EArEkBE,CAAkBr1B,GAEzC,GAAIg1B,EAAgB,CAClB,MAAMhuB,EAASguB,EAAiBA,EAAeltB,OAAO,GAAK,GACrDwtB,EAAmBb,EAAmBztB,GACxCsuB,GAAoBA,EAAiB/yC,QACvC4xC,IACAG,EAAiBttB,GACjBwtB,EAAmBc,IAEnBlB,SAGFA,KAED,CAACL,EAAmB/zB,EAAMy0B,EAAoBN,EAAYC,IAE7D,MAAMmB,EAAgBh9C,YAAY,CAACyG,EAAew2C,GAAa,KAC7D,IAAKx2C,EAAKqC,WAAa2iB,YAAuBhlB,GAC5C,OAGF,MAAMy2C,EAAez2C,EAAKqC,SACrB,IAAGrC,EAAKqC,SACR,uEAEqBwd,wBAAsBoC,yCAC1BjiB,EAAKoB,oDAEpB4jB,YAAuBhlB,SAExB02C,EAAU11B,EAAK21B,YAAY,KACjC,IAAiB,IAAbD,EAAgB,CAClB1B,EAAc,GAAEh0B,EAAK8H,OAAO,EAAG4tB,KAAWD,WAC1C,MAAMG,EAAehzC,SAASizC,eAAetpB,GACxCroB,KACH2C,sBAAsB,KACpBmX,YAAqB43B,EAAcJ,KAKzCpB,KACC,CAACp0B,EAAMuM,EAASynB,EAAcI,IAEjC,MAAO,CACL0B,kBAAmBj8C,EACnBk8C,cAAe1B,EACf2B,iBAAkB5B,EAClBmB,gBACAU,uBAAwB1B,K","file":"0.6531d7c910f326b2774d.js","sourcesContent":["import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { RefObject } from 'react';\nimport React, { FC, useRef, useCallback } from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport useContextMenuPosition from '../../hooks/useContextMenuPosition';\n\nimport RippleEffect from './RippleEffect';\nimport Menu from './Menu';\nimport MenuItem from './MenuItem';\n\nimport './ListItem.scss';\n\ntype OnClickHandler = (e: React.MouseEvent) => void;\n\ntype MenuItemContextAction = {\n title: string;\n icon: string;\n destructive?: boolean;\n handler?: () => void;\n};\n\ntype OwnProps = {\n ref?: RefObject;\n icon?: string;\n className?: string;\n style?: string;\n children: any;\n disabled?: boolean;\n ripple?: boolean;\n narrow?: boolean;\n inactive?: boolean;\n focus?: boolean;\n destructive?: boolean;\n multiline?: boolean;\n contextActions?: MenuItemContextAction[];\n onClick?: OnClickHandler;\n};\n\nconst ListItem: FC = (props) => {\n const {\n ref,\n icon,\n className,\n style,\n children,\n disabled,\n ripple,\n narrow,\n inactive,\n focus,\n destructive,\n multiline,\n contextActions,\n onClick,\n } = props;\n\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(containerRef, !contextActions);\n\n const getTriggerElement = useCallback(() => containerRef.current, []);\n\n const getRootElement = useCallback(\n () => containerRef.current!.closest('.custom-scroll'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => containerRef.current!.querySelector('.ListItem-context-menu .bubble'),\n [],\n );\n\n const { positionX, positionY, style: menuStyle } = useContextMenuPosition(\n contextMenuPosition,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n );\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n return;\n }\n onClick(e);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (inactive || IS_TOUCH_ENV) {\n return;\n }\n if (contextActions && (e.button === 2 || !onClick)) {\n handleBeforeContextMenu(e);\n }\n if (e.button === 0) {\n if (!onClick) {\n handleContextMenu(e);\n } else {\n handleClick(e);\n }\n }\n }, [inactive, contextActions, onClick, handleBeforeContextMenu, handleContextMenu, handleClick]);\n\n const fullClassName = buildClassName(\n 'ListItem no-selection',\n className,\n ripple && 'has-ripple',\n narrow && 'narrow',\n disabled && 'disabled',\n inactive && 'inactive',\n contextMenuPosition && 'has-menu-open',\n focus && 'focus',\n destructive && 'destructive',\n multiline && 'multiline',\n );\n\n return (\n \n \n {icon && (\n \n )}\n {multiline && (
{children}
)}\n {!multiline && children}\n {!disabled && !inactive && ripple && (\n \n )}\n \n {contextActions && contextMenuPosition !== undefined && (\n \n {contextActions.map((action) => (\n \n {action.title}\n \n ))}\n \n )}\n \n );\n};\n\nexport default ListItem;\n","import { RefObject } from 'react';\nimport {\n useEffect, useRef, useCallback, useState,\n} from '../lib/teact/teact';\n\nimport { throttle, debounce } from '../util/schedulers';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\n\ntype TargetCallback = (entry: IntersectionObserverEntry) => void;\ntype RootCallback = (entries: IntersectionObserverEntry[]) => void;\ntype ObserveCleanup = NoneToVoidFunction;\nexport type ObserveFn = (target: HTMLElement, targetCallback?: TargetCallback) => ObserveCleanup;\n\ninterface IntersectionController {\n observer: IntersectionObserver;\n callbacks: Map;\n}\n\ninterface Response {\n observe: ObserveFn;\n freeze: NoneToVoidFunction;\n unfreeze: NoneToVoidFunction;\n}\n\nexport function useIntersectionObserver({\n rootRef,\n throttleMs,\n debounceMs,\n shouldSkipFirst,\n margin,\n threshold,\n isDisabled,\n}: {\n rootRef: RefObject;\n throttleMs?: number;\n debounceMs?: number;\n shouldSkipFirst?: boolean;\n margin?: number;\n threshold?: number | number[];\n isDisabled?: boolean;\n}, rootCallback?: RootCallback): Response {\n const controllerRef = useRef();\n const rootCallbackRef = useRef();\n const isFrozenRef = useRef();\n const onUnfreezeRef = useRef();\n\n rootCallbackRef.current = rootCallback;\n\n const freeze = useCallback(() => {\n isFrozenRef.current = true;\n }, []);\n\n const unfreeze = useCallback(() => {\n isFrozenRef.current = false;\n\n if (onUnfreezeRef.current) {\n onUnfreezeRef.current();\n onUnfreezeRef.current = undefined;\n }\n }, []);\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\n return () => {\n if (controllerRef.current) {\n controllerRef.current.observer.disconnect();\n controllerRef.current.callbacks.clear();\n controllerRef.current = undefined;\n }\n };\n }, [isDisabled]);\n\n function initController() {\n const callbacks = new Map();\n const entriesAccumulator = new Map();\n const observerCallbackSync = () => {\n const entries = Array.from(entriesAccumulator.values());\n\n entries.forEach((entry: IntersectionObserverEntry) => {\n const callback = callbacks.get(entry.target);\n if (callback) {\n callback!(entry, entries);\n }\n });\n\n if (rootCallbackRef.current) {\n rootCallbackRef.current(entries);\n }\n\n entriesAccumulator.clear();\n };\n const scheduler = throttleMs ? throttle : debounceMs ? debounce : undefined;\n const observerCallback = scheduler\n ? scheduler(observerCallbackSync, (throttleMs || debounceMs)!, !shouldSkipFirst)\n : observerCallbackSync;\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n entriesAccumulator.set(entry.target, entry);\n });\n\n if (isFrozenRef.current) {\n onUnfreezeRef.current = () => {\n observerCallback();\n };\n } else {\n observerCallback();\n }\n },\n {\n root: rootRef.current,\n rootMargin: margin ? `${margin}px` : undefined,\n threshold,\n },\n );\n\n controllerRef.current = { observer, callbacks };\n }\n\n const observe = useCallback((target, targetCallback) => {\n if (!controllerRef.current) {\n initController();\n }\n\n const controller = controllerRef.current!;\n controller.observer.observe(target);\n\n if (targetCallback) {\n controller.callbacks.set(target, targetCallback);\n }\n\n return () => {\n if (targetCallback) {\n controller.callbacks.delete(target);\n }\n\n controller.observer.unobserve(target);\n };\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isDisabled]);\n\n return { observe, freeze, unfreeze };\n}\n\nexport function useOnIntersect(\n targetRef: RefObject, observe?: ObserveFn, callback?: TargetCallback,\n) {\n useEffect(() => {\n return observe ? observe(targetRef.current!, callback) : undefined;\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n}\n\nexport function useIsIntersecting(\n targetRef: RefObject, observe?: ObserveFn, callback?: TargetCallback,\n) {\n const [isIntersecting, setIsIntersecting] = useState(!observe);\n\n useOnIntersect(targetRef, observe, (entry) => {\n setIsIntersecting(entry.isIntersecting);\n\n if (callback) {\n callback(entry);\n }\n });\n\n return isIntersecting;\n}\n","import { useEffect } from '../lib/teact/teact';\n\nimport { ApiMediaFormat } from '../api/types';\n\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (\n mediaHash: string | false | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory(mediaHash) : undefined;\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!noLoad && mediaHash && !mediaData) {\n const startedAt = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat).then(() => {\n const spentTime = Date.now() - startedAt;\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, delay]);\n\n return mediaData;\n};\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { selectChatMessages, selectUser } from '../../modules/selectors';\nimport { getUserFullName, getUserStatus, isUserOnline } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n userId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n forceShowSelf?: boolean;\n status?: string;\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n noStatusOrTyping?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n isSavedMessages?: boolean;\n areMessagesLoaded: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst PrivateChatInfo: FC = ({\n typingStatus,\n avatarSize = 'medium',\n status,\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n noStatusOrTyping,\n user,\n isSavedMessages,\n areMessagesLoaded,\n lastSyncTime,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const fullName = getUserFullName(user);\n\n useEffect(() => {\n if (withFullInfo && lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime, withFullInfo]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent, hasPhoto: boolean) => {\n if (user && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: user.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [user, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!user) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (status) {\n return (\n {status}\n );\n }\n\n if (withUpdatingStatus && !areMessagesLoaded) {\n return (\n {lang('Updating')}\n );\n }\n\n if (!user) {\n return undefined;\n }\n\n if (typingStatus) {\n return ;\n }\n\n return (\n
\n {withUsername && user.username && {user.username}}\n {getUserStatus(user, lang)}\n
\n );\n }\n\n return (\n
\n \n
\n {isSavedMessages ? (\n
\n

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {user && user.isVerified && }\n
\n )}\n {(status || (!isSavedMessages && !noStatusOrTyping)) && renderStatusOrTyping()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const areMessagesLoaded = Boolean(selectChatMessages(global, userId));\n\n return {\n lastSyncTime, user, isSavedMessages, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport trapFocus from '../../util/trapFocus';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Portal from './Portal';\n\nimport './Modal.scss';\n\nconst ANIMATION_DURATION = 200;\n\ntype OwnProps = {\n title?: string;\n className?: string;\n isOpen?: boolean;\n header?: FC;\n hasCloseButton?: boolean;\n noBackdrop?: boolean;\n children: any;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onEnter?: () => void;\n};\n\nconst Modal: FC = (props) => {\n const {\n title,\n className,\n isOpen,\n header,\n hasCloseButton,\n noBackdrop,\n children,\n onClose,\n onCloseAnimationEnd,\n onEnter,\n } = props;\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n // eslint-disable-next-line no-null/no-null\n const modalRef = useRef(null);\n\n useEffect(() => (isOpen\n ? captureKeyboardListeners({ onEsc: onClose, onEnter })\n : undefined), [isOpen, onClose, onEnter]);\n useEffect(() => (isOpen && modalRef.current ? trapFocus(modalRef.current) : undefined), [isOpen]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n document.body.classList.toggle('has-open-dialog', isOpen);\n\n if (isOpen || (!isOpen && prevIsOpen !== undefined)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n\n return () => {\n document.body.classList.remove('has-open-dialog');\n };\n }, [isOpen]);\n\n const lang = useLang();\n\n if (!shouldRender) {\n return undefined;\n }\n\n function renderHeader() {\n if (header) {\n return header;\n }\n\n if (!title) {\n return undefined;\n }\n\n return (\n
\n {hasCloseButton && (\n \n \n \n )}\n
{title}
\n
\n );\n }\n\n const fullClassName = buildClassName(\n 'Modal',\n className,\n transitionClassNames,\n noBackdrop && 'transparent-backdrop',\n );\n\n return (\n \n \n
\n
\n
\n {renderHeader()}\n
\n {children}\n
\n
\n
\n
\n
\n );\n};\n\nexport default Modal;\n","export default function trapFocus(element: HTMLElement) {\n function handleKeyDown(e: KeyboardEvent) {\n if (e.key !== 'Tab') {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n const focusableElements = Array.from(\n element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'),\n ) as HTMLElement[];\n if (!focusableElements.length) {\n return;\n }\n\n const currentFocusedIndex = focusableElements.findIndex((em) => em.isSameNode(document.activeElement));\n let newFocusedIndex = 0;\n if (currentFocusedIndex >= 0) {\n if (e.shiftKey) {\n newFocusedIndex = currentFocusedIndex > 0\n ? currentFocusedIndex - 1\n : focusableElements.length - 1;\n } else {\n newFocusedIndex = currentFocusedIndex < focusableElements.length - 1\n ? currentFocusedIndex + 1\n : 0;\n }\n }\n\n focusableElements[newFocusedIndex].focus();\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useLayoutEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Transition.scss';\n\ntype ChildrenFn = (isActive: boolean, isFrom: boolean) => any;\ntype OwnProps = {\n ref?: RefObject;\n activeKey: number;\n name: (\n 'none' | 'slide' | 'mv-slide' | 'slide-fade' | 'zoom-fade' | 'scroll-slide' | 'fade' | 'slide-layers'\n | 'push-slide' | 'reveal'\n );\n direction?: 'auto' | 'inverse' | 1 | -1;\n renderCount?: number;\n shouldRestoreHeight?: boolean;\n shouldCleanup?: boolean;\n id?: string;\n className?: string;\n onStart?: () => void;\n onStop?: () => void;\n children: ChildrenFn;\n};\n\ntype StateProps = {\n animationLevel: number;\n};\n\nconst ANIMATION_DURATION = {\n slide: 450,\n 'mv-slide': 400,\n 'slide-fade': 400,\n 'zoom-fade': 150,\n 'scroll-slide': 500,\n fade: 150,\n 'slide-layers': IS_MOBILE_SCREEN ? 450 : 300,\n 'push-slide': 300,\n reveal: 350,\n};\n\nconst CLEANED_UP = Symbol('CLEANED_UP');\n\nconst Transition: FC = ({\n ref,\n activeKey,\n name,\n direction = 'auto',\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n id,\n className,\n onStart,\n onStop,\n children,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const rendersRef = useRef>({});\n const prevActiveKey = usePrevious(activeKey);\n const activateTimeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n const activeKeyChanged = prevActiveKey !== undefined && activeKey !== prevActiveKey;\n\n if (!renderCount && activeKeyChanged) {\n rendersRef.current = { [prevActiveKey]: rendersRef.current[prevActiveKey] };\n }\n\n rendersRef.current[activeKey] = children;\n\n useLayoutEffect(() => {\n function cleanup() {\n if (!shouldCleanup) {\n return;\n }\n\n rendersRef.current = { [prevActiveKey]: CLEANED_UP };\n forceUpdate();\n }\n\n const container = containerRef.current!;\n\n const childElements = container.children;\n if (childElements.length === 1 && !activeKeyChanged) {\n childElements[0].classList.add('active');\n\n return;\n }\n\n const childNodes = Array.from(container.childNodes);\n\n if (!activeKeyChanged || !childNodes.length) {\n return;\n }\n\n if (activateTimeoutRef.current) {\n clearTimeout(activateTimeoutRef.current);\n activateTimeoutRef.current = undefined;\n }\n\n const isBackwards = (\n direction === -1\n || (direction === 'auto' && prevActiveKey > activeKey)\n || (direction === 'inverse' && prevActiveKey < activeKey)\n );\n\n container.classList.remove('animating');\n container.classList.toggle('backwards', isBackwards);\n\n const keys = Object.keys(rendersRef.current).map(Number);\n const prevActiveIndex = renderCount ? prevActiveKey : keys.indexOf(prevActiveKey);\n const activeIndex = renderCount ? activeKey : keys.indexOf(activeKey);\n\n if (name === 'none' || animationLevel === 0) {\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n cleanup();\n\n return;\n }\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('active');\n node.classList.toggle('from', i === prevActiveIndex);\n node.classList.toggle('through', (\n (i > prevActiveIndex && i < activeIndex) || (i < prevActiveIndex && i > activeIndex)\n ));\n node.classList.toggle('to', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n const width = container.offsetWidth;\n container.scrollBy({\n left: activeIndex > prevActiveIndex ? width : -width,\n behavior: 'smooth',\n });\n }\n\n if (animationLevel > 0) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n }\n\n requestAnimationFrame(() => {\n container.classList.add('animating');\n\n activateTimeoutRef.current = window.setTimeout(() => {\n requestAnimationFrame(() => {\n container.classList.remove('animating', 'backwards');\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n container.scrollLeft = activeKey * container.offsetWidth;\n }\n\n if (shouldRestoreHeight) {\n const activeElement = container.querySelector('.active');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n\n cleanup();\n\n if (onStop) {\n onStop();\n }\n });\n }, ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n\n if (onStart) {\n onStart();\n }\n });\n }, [\n activeKey,\n prevActiveKey,\n activeKeyChanged,\n direction,\n name,\n onStart,\n onStop,\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n animationLevel,\n forceUpdate,\n ]);\n\n useLayoutEffect(() => {\n if (shouldRestoreHeight) {\n const container = containerRef.current!;\n const activeElement = container.querySelector('.active')\n || container.querySelector('.from');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n }, [shouldRestoreHeight, children]);\n\n const renders = rendersRef.current;\n const collection = Object.keys(renderCount ? new Array(renderCount).fill(undefined) : renders).map(Number);\n const contents = collection.map((key) => {\n const render = renders[key];\n\n return (\n typeof render === 'function' ?
{render(key === activeKey, key === prevActiveKey)}
: undefined\n );\n });\n\n const fullClassName = buildClassName(\n 'Transition',\n className,\n animationLevel === 0 && name === 'scroll-slide' ? 'slide' : name,\n );\n\n return (\n
\n {contents}\n
\n );\n};\n\nexport default withGlobal((global) => {\n const { animationLevel } = global.settings.byKey;\n return { animationLevel };\n})(Transition);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiChat, ApiMediaFormat } from '../../api/types';\n\nimport { IS_TEST } from '../../config';\nimport {\n getChatAvatarHash, getChatTitle, isChatPrivate,\n getUserFullName, isUserOnline, isDeletedUser, getUserColorKey,\n} from '../../modules/helpers';\nimport { getFirstLetters } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useLang from '../../hooks/useLang';\n\nimport './Avatar.scss';\n\ntype OwnProps = {\n className?: string;\n size?: 'micro' | 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n withOnlineStatus?: boolean;\n chat?: ApiChat;\n user?: ApiUser;\n text?: string;\n isSavedMessages?: boolean;\n lastSyncTime?: number;\n onClick?: (e: ReactMouseEvent, hasPhoto: boolean) => void;\n};\n\nconst Avatar: FC = ({\n className,\n size = 'large',\n chat,\n user,\n text,\n withOnlineStatus,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const isDeleted = user && isDeletedUser(user);\n let imageHash: string | undefined;\n\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n imageHash = getChatAvatarHash(user);\n } else if (chat) {\n imageHash = getChatAvatarHash(chat);\n }\n }\n\n const dataUri = useMedia(imageHash, false, ApiMediaFormat.DataUri, lastSyncTime);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(dataUri, 'slow');\n\n useLang();\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = ;\n } else if (isDeleted) {\n content = ;\n } else if (shouldRenderFullMedia) {\n content = \"\";\n } else if (user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (chat) {\n const title = getChatTitle(chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else if (text) {\n content = getFirstLetters(text, 2);\n }\n\n const isOnline = !isSavedMessages && user && isUserOnline(user);\n const fullClassName = buildClassName(\n `Avatar size-${size}`,\n className,\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n withOnlineStatus && isOnline && 'online',\n onClick && 'interactive',\n (!isSavedMessages && !shouldRenderFullMedia) && 'no-photo',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (onClick) {\n onClick(e, isSavedMessages || shouldRenderFullMedia);\n }\n }, [onClick, isSavedMessages, shouldRenderFullMedia]);\n\n const senderId = (user || chat) && (user || chat)!.id;\n\n return (\n
\n {typeof content === 'string' ? renderText(content, [size === 'jumbo' ? 'hq_emoji' : 'emoji']) : content}\n
\n );\n};\n\nexport default memo(Avatar);\n","import { RefObject, UIEvent } from 'react';\nimport { LoadMoreDirection } from '../../types';\n\nimport React, {\n FC, useCallback, useEffect, useLayoutEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport resetScroll from '../../util/resetScroll';\n\ntype OwnProps = {\n ref?: RefObject;\n className?: string;\n onLoadMore?: ({ direction }: { direction: LoadMoreDirection }) => void;\n onScroll?: (e: UIEvent) => void;\n items?: any[];\n itemSelector?: string;\n preloadBackwards?: number;\n sensitiveArea?: number;\n noScrollRestore?: boolean;\n noFastList?: boolean;\n cacheBuster?: any;\n children: any;\n};\n\nconst DEFAULT_LIST_SELECTOR = '.ListItem';\nconst DEFAULT_PRELOAD_BACKWARDS = 20;\nconst DEFAULT_SENSITIVE_AREA = 800;\n\nconst InfiniteScroll: FC = ({\n ref,\n className,\n onLoadMore,\n onScroll,\n items,\n itemSelector = DEFAULT_LIST_SELECTOR,\n preloadBackwards = DEFAULT_PRELOAD_BACKWARDS,\n sensitiveArea = DEFAULT_SENSITIVE_AREA,\n // Used to turn off restoring scroll position (e.g. for frequently re-ordered chat or user lists)\n noScrollRestore = false,\n noFastList,\n // Used to re-query `listItemElements` if rendering is delayed by transition\n cacheBuster,\n children,\n}: OwnProps) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const stateRef = useRef<{\n listItemElements: NodeListOf;\n isScrollTopJustUpdated: boolean;\n currentAnchor: HTMLDivElement | undefined;\n currentAnchorTop: number;\n }>({} as any);\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(() => {\n if (!onLoadMore) {\n return [];\n }\n\n return [\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [onLoadMore, items]);\n\n // Initial preload\n useEffect(() => {\n if (!loadMoreBackwards) {\n return;\n }\n\n if (preloadBackwards > 0 && (!items || items.length < preloadBackwards)) {\n loadMoreBackwards();\n return;\n }\n\n const { scrollHeight, clientHeight } = containerRef.current!;\n if (clientHeight && scrollHeight <= clientHeight) {\n loadMoreBackwards();\n }\n }, [items, loadMoreBackwards, preloadBackwards]);\n\n // Restore `scrollTop` after adding items\n useLayoutEffect(() => {\n const container = containerRef.current!;\n const state = stateRef.current;\n\n state.listItemElements = container.querySelectorAll(itemSelector);\n\n if (noScrollRestore) {\n return;\n }\n\n let newScrollTop;\n\n if (state.currentAnchor && Array.from(state.listItemElements).includes(state.currentAnchor)) {\n const { scrollTop } = container;\n const newAnchorTop = state.currentAnchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - state.currentAnchorTop);\n } else {\n const nextAnchor = state.listItemElements[0];\n if (nextAnchor && nextAnchor.offsetParent) {\n state.currentAnchor = nextAnchor;\n state.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n\n resetScroll(container, newScrollTop);\n\n state.isScrollTopJustUpdated = true;\n }, [noScrollRestore, itemSelector, items, cacheBuster]);\n\n const handleScroll = useCallback((e: UIEvent) => {\n if (loadMoreForwards && loadMoreBackwards) {\n const {\n listItemElements, isScrollTopJustUpdated, currentAnchor, currentAnchorTop,\n } = stateRef.current;\n\n if (isScrollTopJustUpdated) {\n stateRef.current.isScrollTopJustUpdated = false;\n return;\n }\n\n const listLength = listItemElements.length;\n const container = containerRef.current!;\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const top = listLength ? listItemElements[0].offsetTop : 0;\n const isNearTop = scrollTop <= top + sensitiveArea;\n const bottom = listLength\n ? listItemElements[listLength - 1].offsetTop + listItemElements[listLength - 1].offsetHeight\n : scrollHeight;\n const isNearBottom = bottom - (scrollTop + offsetHeight) <= sensitiveArea;\n let isUpdated = false;\n\n if (isNearTop) {\n const nextAnchor = listItemElements[0];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingUp = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop > currentAnchorTop\n );\n\n if (isMovingUp) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreForwards();\n }\n }\n }\n\n if (isNearBottom) {\n const nextAnchor = listItemElements[listLength - 1];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingDown = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop < currentAnchorTop\n );\n\n if (isMovingDown) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreBackwards();\n }\n }\n }\n\n if (!isUpdated) {\n if (currentAnchor && currentAnchor.offsetParent) {\n stateRef.current.currentAnchorTop = currentAnchor.getBoundingClientRect().top;\n } else {\n const nextAnchor = listItemElements[0];\n\n if (nextAnchor) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n }\n }\n\n if (onScroll) {\n onScroll(e);\n }\n }, [loadMoreBackwards, loadMoreForwards, onScroll, sensitiveArea]);\n\n return (\n
\n {children}\n
\n );\n};\n\nexport default InfiniteScroll;\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import { useEffect, useRef, useState } from '../lib/teact/teact';\n\nimport useShowTransition from './useShowTransition';\n\nconst SPEED = {\n fast: 200,\n slow: 350,\n};\n\nexport default (mediaData?: any, speed: keyof typeof SPEED = 'fast', noAnimate = false) => {\n const isMediaLoaded = Boolean(mediaData);\n const willAnimate = !useRef(isMediaLoaded).current && !noAnimate;\n const [shouldRenderThumb, setShouldRenderThumb] = useState(!isMediaLoaded);\n\n const {\n shouldRender: shouldRenderFullMedia,\n transitionClassNames,\n } = useShowTransition(isMediaLoaded, undefined, !willAnimate, speed);\n\n useEffect(() => {\n if (shouldRenderFullMedia) {\n if (willAnimate) {\n setTimeout(() => {\n setShouldRenderThumb(false);\n }, SPEED[speed]);\n } else {\n setShouldRenderThumb(false);\n }\n }\n }, [willAnimate, shouldRenderFullMedia, speed]);\n\n return {\n shouldRenderThumb,\n shouldRenderFullMedia,\n transitionClassNames,\n };\n};\n","import { ApiPhoto, ApiVideo, ApiSticker } from '../../../api/types';\nimport { getPhotoInlineDimensions, getVideoDimensions, IDimensions } from '../../../modules/helpers';\nimport windowSize from '../../../util/windowSize';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { STICKER_SIZE_INLINE_DESKTOP_FACTOR, STICKER_SIZE_INLINE_MOBILE_FACTOR } from '../../../config';\n\nexport const MEDIA_VIEWER_MEDIA_QUERY = '(max-height: 640px)';\nexport const REM = parseInt(getComputedStyle(document.documentElement).fontSize, 10);\nexport const ROUND_VIDEO_DIMENSIONS = 200;\nexport const AVATAR_FULL_DIMENSIONS = { width: 640, height: 640 };\n\nconst DEFAULT_MEDIA_DIMENSIONS: IDimensions = { width: 100, height: 100 };\nconst LIKE_STICKER_ID = '1258816259753933';\nconst MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH = 0.69;\n\nlet cachedMaxWidth: number | undefined;\n\nfunction getMaxMessageWidthRem(fromOwnMessage: boolean) {\n const regularMaxWidth = fromOwnMessage ? 30 : 29;\n if (!IS_MOBILE_SCREEN) {\n return regularMaxWidth;\n }\n\n // @optimization Limitation: changing device screen width not supported\n if (!cachedMaxWidth) {\n cachedMaxWidth = Math.min(\n regularMaxWidth,\n Math.floor(window.innerWidth * MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH) / REM,\n );\n }\n\n return cachedMaxWidth;\n}\n\nfunction getAvailableWidth(\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const extraPaddingRem = isForwarded || isWebPagePhoto ? 1.625 : 0;\n const availableWidthRem = getMaxMessageWidthRem(fromOwnMessage) - extraPaddingRem;\n\n return availableWidthRem * REM;\n}\n\nfunction getAvailableHeight(isGif?: boolean, aspectRatio?: number) {\n if (\n isGif && aspectRatio\n && aspectRatio >= 0.75 && aspectRatio <= 1.25\n ) {\n return 20 * REM;\n }\n\n return 27 * REM;\n}\n\nfunction calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n isGif,\n}: {\n width: number;\n height: number;\n fromOwnMessage: boolean;\n isForwarded?: boolean;\n isWebPagePhoto?: boolean;\n isGif?: boolean;\n}): IDimensions {\n const aspectRatio = height / width;\n const availableWidth = getAvailableWidth(fromOwnMessage, isForwarded, isWebPagePhoto);\n const availableHeight = getAvailableHeight(isGif, aspectRatio);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function getMediaViewerAvailableDimensions(withFooter: boolean, isVideo: boolean): IDimensions {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n const { width: windowWidth, height: windowHeight } = windowSize.get();\n let occupiedHeightRem = isVideo && mql.matches ? 10 : 8.25;\n if (withFooter) {\n occupiedHeightRem = mql.matches ? 10 : 15;\n }\n\n return {\n width: windowWidth,\n height: windowHeight - occupiedHeightRem * REM,\n };\n}\n\nexport function calculateInlineImageDimensions(\n photo: ApiPhoto,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const { width, height } = getPhotoInlineDimensions(photo) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n });\n}\n\nexport function calculateVideoDimensions(\n video: ApiVideo,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n) {\n const { width, height } = getVideoDimensions(video) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isGif: video.isGif,\n });\n}\n\nexport function getPictogramDimensions(): IDimensions {\n return {\n width: 2 * REM,\n height: 2 * REM,\n };\n}\n\nexport function getDocumentThumbnailDimensions(smaller?: boolean): IDimensions {\n if (smaller) {\n return {\n width: 3 * REM,\n height: 3 * REM,\n };\n }\n\n return {\n width: 3.375 * REM,\n height: 3.375 * REM,\n };\n}\n\nexport function getStickerDimensions(sticker: ApiSticker): IDimensions {\n const { width } = sticker;\n let { height } = sticker;\n\n // For some reason this sticker has some weird `height` value\n if (sticker.id === LIKE_STICKER_ID) {\n height = width;\n }\n\n const aspectRatio = (height && width) && height / width;\n const baseWidth = (IS_MOBILE_SCREEN ? STICKER_SIZE_INLINE_MOBILE_FACTOR : STICKER_SIZE_INLINE_DESKTOP_FACTOR) * REM;\n const calculatedHeight = aspectRatio ? baseWidth * aspectRatio : baseWidth;\n\n if (aspectRatio && calculatedHeight > baseWidth) {\n return {\n width: Math.round(baseWidth / aspectRatio),\n height: baseWidth,\n };\n }\n\n return {\n width: baseWidth,\n height: calculatedHeight,\n };\n}\n\nexport function calculateMediaViewerDimensions(\n { width, height }: IDimensions, withFooter: boolean, isVideo: boolean = false,\n): IDimensions {\n const { width: availableWidth, height: availableHeight } = getMediaViewerAvailableDimensions(withFooter, isVideo);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function calculateDimensions(\n availableWidth: number,\n availableHeight: number,\n mediaWidth: number,\n mediaHeight: number,\n): IDimensions {\n const aspectRatio = mediaHeight / mediaWidth;\n const calculatedWidth = Math.min(mediaWidth, availableWidth);\n const calculatedHeight = Math.round(calculatedWidth * aspectRatio);\n\n if (calculatedHeight > availableHeight) {\n return {\n width: Math.round(availableHeight / aspectRatio),\n height: availableHeight,\n };\n }\n\n return {\n width: calculatedWidth,\n height: Math.round(calculatedWidth * aspectRatio),\n };\n}\n","import React, {\n FC, useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_IOS } from '../../util/environment';\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\ntype OwnProps = {\n className?: string;\n id: string;\n animationData: AnyLiteral;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n onLoad?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise;\nlet RLottie: RLottieClass;\n\n// Time supposed for judges to measure \"Transferred Size\" in Dev Tools\nconst LOTTIE_LOAD_DELAY = 5000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC = ({\n className,\n id,\n animationData,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n onLoad,\n}) => {\n const [animation, setAnimation] = useState();\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !animationData) {\n return;\n }\n\n const exec = () => {\n if (!container.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n id,\n container.current,\n animationData,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (container.current) {\n exec();\n }\n });\n });\n }\n }, [animation, animationData, id, isLowPriority, noLoop, onLoad, quality, size, speed]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else if (shouldRestart) {\n animation.goToAndPlay(0);\n } else {\n animation.play();\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation();\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n const fullClassName = buildClassName(\n 'AnimatedSticker',\n className,\n // Workaround for an iOS bug when animated stickers sometimes disappear\n IS_IOS && play && 'is-playing',\n );\n\n const style = size ? `width: ${size}px; height: ${size}px;` : undefined;\n\n return (\n \n );\n};\n\nexport default memo(AnimatedSticker);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\nimport { TextPart } from '../common/helpers/renderMessageText';\n\nimport Modal from './Modal';\nimport Button from './Button';\n\ntype OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n header?: FC;\n textParts?: TextPart[];\n text?: string;\n confirmLabel?: string;\n confirmHandler: () => void;\n confirmIsDestructive?: boolean;\n isButtonsInOneRow?: boolean;\n};\n\nconst ConfirmDialog: FC = ({\n isOpen,\n onClose,\n onCloseAnimationEnd,\n header,\n text,\n textParts,\n confirmLabel = 'Confirm',\n confirmHandler,\n confirmIsDestructive,\n isButtonsInOneRow,\n}) => {\n const lang = useLang();\n\n return (\n \n {text && text.split('\\\\n').map((textPart) => (\n

{textPart}

\n ))}\n {textParts}\n
\n \n {confirmLabel}\n \n \n
\n \n );\n};\n\nexport default memo(ConfirmDialog);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\n\nimport './NothingFound.scss';\n\ninterface OwnProps {\n text?: string;\n}\n\nconst DEFAULT_TEXT = 'Nothing found.';\n\nconst NothingFound: FC = ({ text = DEFAULT_TEXT }) => {\n const { transitionClassNames } = useShowTransition(true);\n\n return (\n
\n {text}\n
\n );\n};\n\nexport default memo(NothingFound);\n","import { useEffect, useRef } from '../../../lib/teact/teact';\n\nimport useOnChange from '../../../hooks/useOnChange';\nimport useForceUpdate from '../../../hooks/useForceUpdate';\n\nexport default function useAsyncRendering(dependencies: T, delay?: number) {\n const isDisabled = delay === undefined;\n const shouldRenderRef = useRef(isDisabled);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n if (isDisabled) {\n return;\n }\n\n shouldRenderRef.current = false;\n\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n }, dependencies);\n\n useEffect(() => {\n if (isDisabled || shouldRenderRef.current) {\n return;\n }\n\n const exec = () => {\n shouldRenderRef.current = true;\n forceUpdate();\n };\n\n if (delay! > 0) {\n timeoutRef.current = window.setTimeout(exec, delay);\n } else {\n exec();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n\n return shouldRenderRef.current;\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({ children, className, onClick }) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","import {\n useEffect, useMemo, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { IS_PROGRESSIVE_SUPPORTED } from '../util/environment';\nimport { ApiMediaFormat } from '../api/types';\nimport { throttle } from '../util/schedulers';\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nconst STREAMING_PROGRESS = 0.75;\nconst STREAMING_TIMEOUT = 1500;\nconst PROGRESS_THROTTLE = 500;\n\nexport default (\n mediaHash: string | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory(mediaHash) : undefined;\n const isStreaming = mediaFormat === ApiMediaFormat.Stream || (\n IS_PROGRESSIVE_SUPPORTED && mediaFormat === ApiMediaFormat.Progressive\n );\n const forceUpdate = useForceUpdate();\n const [downloadProgress, setDownloadProgress] = useState(mediaData && !isStreaming ? 1 : 0);\n const startedAtRef = useRef();\n\n const handleProgress = useMemo(() => {\n return throttle((progress: number) => {\n if (!delay || (Date.now() - startedAtRef.current! > delay)) {\n setDownloadProgress(progress);\n }\n }, PROGRESS_THROTTLE, true);\n }, [delay]);\n\n useEffect(() => {\n if (!noLoad && mediaHash) {\n if (!mediaData) {\n setDownloadProgress(0);\n\n if (startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n }\n\n startedAtRef.current = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat, handleProgress).then(() => {\n const spentTime = Date.now() - startedAtRef.current!;\n startedAtRef.current = undefined;\n\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n } else if (isStreaming) {\n setTimeout(() => {\n setDownloadProgress(STREAMING_PROGRESS);\n }, STREAMING_TIMEOUT);\n }\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, isStreaming, delay, handleProgress]);\n\n useEffect(() => {\n if (noLoad && startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n setDownloadProgress(0);\n }\n }, [handleProgress, noLoad]);\n\n return { mediaData, downloadProgress };\n};\n","import React, {\n FC, useEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './ProgressSpinner.scss';\n\nconst RADIUSES = {\n s: 22, m: 25, l: 28, xl: 20,\n};\nconst STROKE_WIDTH = 2;\nconst MIN_PROGRESS = 0.05;\nconst MAX_PROGRESS = 1;\n\nconst ProgressSpinner: FC<{\n progress?: number;\n size?: 's' | 'm' | 'l' | 'xl';\n square?: boolean;\n transparent?: boolean;\n noCross?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n}> = ({\n progress = 0,\n size = 'l',\n square,\n transparent,\n noCross,\n onClick,\n}) => {\n const radius = RADIUSES[size];\n const circleRadius = radius - STROKE_WIDTH * 2;\n const borderRadius = radius - 1;\n const circumference = circleRadius * 2 * Math.PI;\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n\n useEffect(() => {\n if (!container.current) {\n return;\n }\n\n const svg = container.current.firstElementChild;\n const strokeDashOffset = circumference - Math.min(Math.max(MIN_PROGRESS, progress), MAX_PROGRESS) * circumference;\n\n if (!svg) {\n container.current.innerHTML = `\n \n `;\n } else {\n (svg.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n }, [container, circumference, borderRadius, circleRadius, progress]);\n\n const className = buildClassName(\n `ProgressSpinner size-${size}`,\n transparent && 'transparent',\n square && 'square',\n noCross && 'no-cross',\n );\n\n return (\n \n );\n};\n\nexport default memo(ProgressSpinner);\n","import { FC, useRef, useLayoutEffect } from '../../lib/teact/teact';\nimport TeactDOM from '../../lib/teact/teact-dom';\n\ntype OwnProps = {\n containerId?: string;\n className?: string;\n children: any;\n};\n\nconst Portal: FC = ({ containerId, className, children }) => {\n const elementRef = useRef(document.createElement('div'));\n\n useLayoutEffect(() => {\n const container = document.querySelector(containerId || '#portals');\n if (!container) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (className) {\n element.classList.add(className);\n }\n\n container.appendChild(element);\n\n return () => {\n TeactDOM.render(undefined, element);\n container.removeChild(element);\n };\n }, [className, containerId]);\n\n return TeactDOM.render(children, elementRef.current);\n};\n\nexport default Portal;\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport {\n getChatTypeString,\n getChatTitle,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport { selectChat, selectChatMessages, selectChatOnlineCount } from '../../modules/selectors';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n chatId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'small' | 'medium' | 'large' | 'jumbo';\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n withChatType?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n onlineCount?: number;\n areMessagesLoaded: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst GroupChatInfo: FC = ({\n typingStatus,\n avatarSize = 'medium',\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n withChatType,\n chat,\n onlineCount,\n areMessagesLoaded,\n lastSyncTime,\n loadFullChat,\n openMediaViewer,\n}) => {\n const isSuperGroup = chat && isChatSuperGroup(chat);\n const { id: chatId, isMin, isRestricted } = chat || {};\n\n useEffect(() => {\n if (chatId && !isMin && withFullInfo && lastSyncTime) {\n loadFullChat({ chatId });\n }\n }, [chatId, isMin, lastSyncTime, withFullInfo, loadFullChat, isSuperGroup]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent, hasPhoto: boolean) => {\n if (chat && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: chat.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [chat, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (withUpdatingStatus && !areMessagesLoaded && !isRestricted) {\n return (\n {lang('Updating')}\n );\n }\n\n if (!chat) {\n return undefined;\n }\n\n if (typingStatus) {\n return ;\n }\n\n if (withChatType) {\n return (\n
{lang(getChatTypeString(chat))}
\n );\n }\n\n const handle = withUsername ? chat.username : undefined;\n const groupStatus = getGroupStatus(chat, lang);\n const onlineStatus = onlineCount ? `, ${lang('OnlineCount', onlineCount, 'i')}` : undefined;\n\n return (\n
\n {handle && {handle}}\n {groupStatus}\n {onlineStatus && {onlineStatus}}\n
\n );\n }\n\n return (\n
\n \n
\n
\n

{renderText(getChatTitle(chat))}

\n {chat.isVerified && }\n
\n {renderStatusOrTyping()}\n
\n
\n );\n};\n\nfunction getGroupStatus(chat: ApiChat, lang: LangFn) {\n const chatTypeString = lang(getChatTypeString(chat));\n const { membersCount } = chat;\n\n if (chat.isRestricted) {\n return chatTypeString === 'Channel' ? 'channel is inaccessible' : 'group is inaccessible';\n }\n\n if (!membersCount) {\n return chatTypeString;\n }\n\n return chatTypeString === 'Channel'\n ? lang('Subscribers', membersCount, 'i')\n : lang('Members', membersCount, 'i');\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const { lastSyncTime } = global;\n const chat = selectChat(global, chatId);\n const onlineCount = chat ? selectChatOnlineCount(global, chat) : undefined;\n const areMessagesLoaded = Boolean(selectChatMessages(global, chatId));\n\n return {\n lastSyncTime, chat, onlineCount, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullChat', 'openMediaViewer']),\n)(GroupChatInfo));\n","import { FocusDirection } from '../types';\n\nimport { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck';\nimport { fastRaf } from './schedulers';\nimport { animateSingle } from './animation';\n\nconst MAX_DISTANCE = 1500;\nconst MIN_JS_DURATION = 250;\nconst MAX_JS_DURATION = 600;\n\nlet isAnimating = false;\n\nexport default function fastSmoothScroll(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n maxDistance = MAX_DISTANCE,\n forceDirection?: FocusDirection,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n if (forceDirection === FocusDirection.Static) {\n element.scrollIntoView({ block: position });\n\n return;\n }\n\n const { offsetTop } = element;\n\n if (forceDirection === undefined) {\n const offset = offsetTop - container.scrollTop;\n\n if (offset < -maxDistance) {\n container.scrollTop += (offset + maxDistance);\n } else if (offset > maxDistance) {\n container.scrollTop += (offset - maxDistance);\n }\n } else if (forceDirection === FocusDirection.Up) {\n container.scrollTop = offsetTop + maxDistance;\n } else if (forceDirection === FocusDirection.Down) {\n container.scrollTop = Math.max(0, offsetTop - maxDistance);\n }\n\n isAnimating = true;\n fastRaf(() => {\n dispatchHeavyAnimationEvent(MAX_JS_DURATION);\n scrollWithJs(container, element, position, margin, forceDuration, forceCurrentContainerHeight);\n });\n}\n\nexport function isAnimatingScroll() {\n return isAnimating;\n}\n\nfunction scrollWithJs(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n const { offsetTop: elementTop, offsetHeight: elementHeight } = element;\n const { scrollTop, offsetHeight: containerHeight, scrollHeight } = container;\n const targetContainerHeight = !forceCurrentContainerHeight && container.dataset.normalHeight\n ? Number(container.dataset.normalHeight)\n : containerHeight;\n\n let path!: number;\n\n switch (position) {\n case 'start':\n path = (elementTop - margin) - scrollTop;\n break;\n case 'end':\n path = (elementTop + elementHeight + margin) - (scrollTop + targetContainerHeight);\n break;\n // 'nearest' is not supported yet\n case 'nearest':\n case 'center':\n path = elementHeight < targetContainerHeight\n ? (elementTop + elementHeight / 2) - (scrollTop + targetContainerHeight / 2)\n : (elementTop - margin) - scrollTop;\n break;\n }\n\n if (path < 0) {\n const remainingPath = -scrollTop;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollHeight - (scrollTop + targetContainerHeight);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollTop + path;\n const duration = forceDuration || (\n MIN_JS_DURATION + (Math.abs(path) / MAX_DISTANCE) * (MAX_JS_DURATION - MIN_JS_DURATION)\n );\n const startAt = Date.now();\n\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / duration, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollTop = Math.round(target - currentPath);\n\n isAnimating = t < 1;\n\n return isAnimating;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport Spinner from './Spinner';\n\nimport './Radio.scss';\n\ntype OwnProps = {\n id?: string;\n name: string;\n label: string;\n subLabel?: string;\n value: string;\n checked: boolean;\n disabled?: boolean;\n hidden?: boolean;\n isLoading?: boolean;\n onChange: (e: ChangeEvent) => void;\n};\n\nconst Radio: FC = ({\n id,\n label,\n subLabel,\n value,\n name,\n checked,\n disabled,\n hidden,\n isLoading,\n onChange,\n}) => {\n const className = buildClassName(\n 'Radio',\n disabled && 'disabled',\n hidden && 'hidden-widget',\n isLoading && 'loading',\n );\n\n return (\n \n );\n};\n\nexport default memo(Radio);\n","import { ChangeEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport Radio from './Radio';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n hidden?: boolean;\n};\n\ntype OwnProps = {\n id?: string;\n name: string;\n options: IRadioOption[];\n selected?: string;\n disabled?: boolean;\n loadingOption?: string;\n onChange: (value: string) => void;\n};\n\nconst RadioGroup: FC = ({\n id,\n name,\n options,\n selected,\n disabled,\n loadingOption,\n onChange,\n}) => {\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value } = event.currentTarget;\n onChange(value);\n }, [onChange]);\n\n return (\n
\n {options.map((option) => (\n
\n );\n};\n\nexport default memo(RadioGroup);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\nimport { LoadMoreDirection } from '../types';\n\nimport { areSortedArraysEqual } from '../util/iteratees';\nimport useForceUpdate from './useForceUpdate';\nimport usePrevious from './usePrevious';\n\ntype GetMore = (args: { direction: LoadMoreDirection }) => void;\ntype LoadMoreBackwards = (args: { offsetId?: number }) => void;\n\nconst DEFAULT_LIST_SLICE = 30;\n\nexport default (\n loadMoreBackwards?: LoadMoreBackwards,\n listIds?: number[],\n isDisabled = false,\n listSlice = DEFAULT_LIST_SLICE,\n forceFullPreload = false,\n): [number[]?, GetMore?] => {\n const lastParamsRef = useRef<{\n direction?: LoadMoreDirection;\n offsetId?: number;\n }>();\n\n const viewportIdsRef = useRef((() => {\n // Only run once to initialize\n if (!listIds || lastParamsRef.current) {\n return undefined;\n }\n\n const { newViewportIds } = getViewportSlice(listIds, listIds[0], LoadMoreDirection.Forwards, listSlice);\n return newViewportIds;\n })());\n\n const forceUpdate = useForceUpdate();\n\n const prevListIds = usePrevious(listIds);\n const prevIsDisabled = usePrevious(isDisabled);\n if (listIds && !isDisabled && (listIds !== prevListIds || isDisabled !== prevIsDisabled)) {\n const { offsetId = listIds[0], direction = LoadMoreDirection.Forwards } = lastParamsRef.current || {};\n const { newViewportIds } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (!viewportIdsRef.current || !areSortedArraysEqual(viewportIdsRef.current, newViewportIds)) {\n viewportIdsRef.current = newViewportIds;\n }\n }\n\n useEffect(() => {\n if (listIds && !isDisabled && loadMoreBackwards && forceFullPreload) {\n const viewportIds = viewportIdsRef.current!;\n loadMoreBackwards({ offsetId: viewportIds[viewportIds.length - 1] });\n }\n }, [listIds, isDisabled, loadMoreBackwards, forceFullPreload]);\n\n const getMore: GetMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n const viewportIds = viewportIdsRef.current;\n\n const offsetId = viewportIds\n ? direction === LoadMoreDirection.Backwards ? viewportIds[viewportIds.length - 1] : viewportIds[0]\n : undefined;\n\n if (!listIds) {\n if (loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n\n return;\n }\n\n lastParamsRef.current = { ...lastParamsRef.current, direction, offsetId };\n\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (areSomeLocal && !(viewportIds && areSortedArraysEqual(viewportIds, newViewportIds))) {\n viewportIdsRef.current = newViewportIds;\n forceUpdate();\n }\n\n if (!areAllLocal && loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n }, [listIds, listSlice, loadMoreBackwards, forceUpdate]);\n\n return isDisabled ? [listIds] : [viewportIdsRef.current, getMore];\n};\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId = 0,\n direction: LoadMoreDirection,\n listSlice: number,\n) {\n const { length } = sourceIds;\n const index = sourceIds.indexOf(offsetId);\n const isForwards = direction === LoadMoreDirection.Forwards;\n const indexForDirection = isForwards ? index : (index + 1) || length;\n const from = Math.max(0, indexForDirection - listSlice);\n const to = indexForDirection + listSlice - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { STICKER_SIZE_TWO_FA } from '../../config';\nimport { getStickerDimensions } from './helpers/mediaDimensions';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './AnimatedEmoji.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n observeIntersection?: ObserveFn;\n isInline?: boolean;\n lastSyncTime?: number;\n};\n\nconst QUALITY = 1;\nconst RESIZE_FACTOR = 0.5;\n\nconst AnimatedEmoji: FC = ({\n sticker, isInline = false, observeIntersection, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isAnimationLoaded, markAnimationLoaded] = useFlag();\n const localMediaHash = `sticker${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl, lastSyncTime);\n const { transitionClassNames } = useTransitionForMedia(previewBlobUrl, 'slow');\n\n const mediaData = useMedia(localMediaHash, !isIntersecting, ApiMediaFormat.Lottie, lastSyncTime);\n const isMediaLoaded = Boolean(mediaData);\n\n const [playKey, setPlayKey] = useState(String(Math.random()));\n const handleClick = useCallback(() => {\n setPlayKey(String(Math.random()));\n }, []);\n\n let width: number;\n if (isInline) {\n width = getStickerDimensions(sticker).width * RESIZE_FACTOR;\n } else {\n width = STICKER_SIZE_TWO_FA;\n }\n\n const style = `width: ${width}px; height: ${width}px;`;\n\n return (\n \n {previewBlobUrl && !isAnimationLoaded && (\n \"\"\n )}\n {isMediaLoaded && (\n \n )}\n \n );\n};\n\nexport default AnimatedEmoji;\n","export enum SwipeDirection {\n Up,\n Down,\n Left,\n Right,\n}\n\ninterface CaptureOptions {\n onCapture?: (e: MouseEvent | TouchEvent) => void;\n onRelease?: (e: MouseEvent | TouchEvent) => void;\n onDrag?: (\n e: MouseEvent | TouchEvent,\n captureEvent: MouseEvent | TouchEvent,\n params: {\n dragOffsetX: number;\n dragOffsetY: number;\n },\n ) => void;\n onSwipe?: (e: Event, direction: SwipeDirection) => void;\n onClick?: (e: MouseEvent | TouchEvent) => void;\n excludedClosestSelector?: string;\n withCursor?: boolean;\n}\n\n// https://stackoverflow.com/questions/11287877/how-can-i-get-e-offsetx-on-mobile-ipad\n// Android does not have this value, and iOS has it but as read-only\nexport interface RealTouchEvent extends TouchEvent {\n pageX?: number;\n pageY?: number;\n}\n\nconst MOVED_THRESHOLD = 15;\nconst SWIPE_THRESHOLD = 50;\n\nexport function captureEvents(element: HTMLElement, options: CaptureOptions) {\n let captureEvent: MouseEvent | RealTouchEvent | undefined;\n let hasMoved = false;\n\n function onCapture(e: MouseEvent | RealTouchEvent) {\n if (options.excludedClosestSelector && (\n (e.target as HTMLElement).matches(options.excludedClosestSelector)\n || (e.target as HTMLElement).closest(options.excludedClosestSelector)\n )) {\n return;\n }\n\n captureEvent = e;\n\n if (e.type === 'mousedown') {\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onRelease);\n } else if (e.type === 'touchstart') {\n document.addEventListener('touchmove', onMove);\n document.addEventListener('touchend', onRelease);\n document.addEventListener('touchcancel', onRelease);\n\n if ('touches' in e) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n }\n\n document.body.classList.add('no-selection');\n if (options.withCursor) {\n document.body.classList.add('cursor-grabbing');\n }\n\n if (options.onCapture) {\n options.onCapture(e);\n }\n }\n\n function onRelease(e: MouseEvent | TouchEvent) {\n if (captureEvent) {\n if (options.withCursor) {\n document.body.classList.remove('cursor-grabbing');\n }\n document.body.classList.remove('no-selection');\n\n document.removeEventListener('mouseup', onRelease);\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('touchcancel', onRelease);\n document.removeEventListener('touchend', onRelease);\n document.removeEventListener('touchmove', onMove);\n\n captureEvent = undefined;\n\n if (hasMoved) {\n if (options.onRelease) {\n options.onRelease(e);\n }\n } else if (options.onClick) {\n options.onClick(e);\n }\n }\n\n hasMoved = false;\n }\n\n function onMove(e: MouseEvent | RealTouchEvent) {\n if (captureEvent) {\n if (e.type === 'touchmove' && ('touches' in e)) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n\n const dragOffsetX = e.pageX! - captureEvent.pageX!;\n const dragOffsetY = e.pageY! - captureEvent.pageY!;\n\n if (Math.abs(dragOffsetX) >= MOVED_THRESHOLD || Math.abs(dragOffsetY) >= MOVED_THRESHOLD) {\n hasMoved = true;\n }\n\n if (options.onDrag) {\n options.onDrag(e, captureEvent, { dragOffsetX, dragOffsetY });\n }\n\n if (options.onSwipe) {\n processSwipe(e, dragOffsetX, dragOffsetY, options.onSwipe);\n }\n }\n }\n\n element.addEventListener('mousedown', onCapture);\n element.addEventListener('touchstart', onCapture, { passive: true });\n\n return () => {\n element.removeEventListener('mousedown', onCapture);\n element.removeEventListener('touchstart', onCapture);\n };\n}\n\nfunction processSwipe(\n e: Event, dragOffsetX: number, dragOffsetY: number, onSwipe: (e: Event, direction: SwipeDirection) => void,\n) {\n const xAbs = Math.abs(dragOffsetX);\n const yAbs = Math.abs(dragOffsetY);\n\n if (dragOffsetX && dragOffsetY) {\n const ratio = Math.max(xAbs, yAbs) / Math.min(xAbs, yAbs);\n // Diagonal swipe\n if (ratio < 2) {\n return;\n }\n }\n\n if (xAbs >= SWIPE_THRESHOLD) {\n if (dragOffsetX < 0) {\n onSwipe(e, SwipeDirection.Left);\n } else {\n onSwipe(e, SwipeDirection.Right);\n }\n } else if (yAbs >= SWIPE_THRESHOLD) {\n if (dragOffsetY < 0) {\n onSwipe(e, SwipeDirection.Up);\n } else {\n onSwipe(e, SwipeDirection.Down);\n }\n }\n}\n","import React, { FC } from '../../lib/teact/teact';\n\nimport './VerifiedIcon.scss';\n\nconst VerifiedIcon: FC = () => {\n return (\n \n );\n};\n\nexport default VerifiedIcon;\n","import React, { useCallback, useMemo, useState } from '../lib/teact/teact';\nimport { debounce } from '../util/schedulers';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\n\ntype BufferingEvent = (e: Event | React.SyntheticEvent) => void;\n\nconst MIN_READY_STATE = 3;\n// Avoid flickering when re-mounting previously buffered video\nconst DEBOUNCE = 200;\n\nexport default (noInitiallyBuffered = false) => {\n const [isBuffered, setIsBuffered] = useState(!noInitiallyBuffered);\n const [bufferedProgress, setBufferedProgress] = useState(0);\n\n const setIsBufferedDebounced = useMemo(() => {\n return debounce(setIsBuffered, DEBOUNCE, false, true);\n }, []);\n\n const handleBuffering = useCallback((e) => {\n const media = e.currentTarget as HTMLMediaElement;\n\n if (!isSafariPatchInProgress(media)) {\n if (media.buffered.length) {\n setBufferedProgress(media.buffered.end(0) / media.duration);\n }\n\n setIsBufferedDebounced(media.readyState >= MIN_READY_STATE || media.currentTime > 0);\n }\n }, [setIsBufferedDebounced]);\n\n const bufferingHandlers = {\n onLoadedData: handleBuffering,\n onPlaying: handleBuffering,\n onLoadStart: handleBuffering, // Needed for Safari to start\n onPause: handleBuffering, // Needed for Chrome when seeking\n onTimeUpdate: handleBuffering, // Needed for audio buffering progress\n onProgress: handleBuffering, // Needed for video buffering progress\n };\n\n return {\n isBuffered,\n bufferedProgress,\n bufferingHandlers,\n checkBuffering(element: HTMLMediaElement) {\n setIsBufferedDebounced(element.readyState >= MIN_READY_STATE);\n },\n };\n};\n","export default function focusEditableElement(element: HTMLElement, force?: boolean) {\n if (!force && element === document.activeElement) {\n return;\n }\n const selection = window.getSelection()!;\n const range = document.createRange();\n\n if (!element.lastChild || !element.lastChild.nodeValue) {\n element.focus();\n return;\n }\n\n range.setStart(element.lastChild, element.lastChild.nodeValue.length);\n selection.removeAllRanges();\n selection.addRange(range);\n}\n","import { ApiMessageEntity, ApiMessageEntityTypes, ApiFormattedText } from '../../../../api/types';\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nconst ENTITY_CLASS_BY_NODE_NAME: Record = {\n B: ApiMessageEntityTypes.Bold,\n STRONG: ApiMessageEntityTypes.Bold,\n I: ApiMessageEntityTypes.Italic,\n EM: ApiMessageEntityTypes.Italic,\n U: ApiMessageEntityTypes.Underline,\n S: ApiMessageEntityTypes.Strike,\n STRIKE: ApiMessageEntityTypes.Strike,\n DEL: ApiMessageEntityTypes.Strike,\n CODE: ApiMessageEntityTypes.Code,\n PRE: ApiMessageEntityTypes.Pre,\n BLOCKQUOTE: ApiMessageEntityTypes.Blockquote,\n};\n\nconst MAX_TAG_DEEPNESS = 3;\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default function parseMessageInput(html: string): ApiFormattedText {\n const fragment = document.createElement('div');\n fragment.innerHTML = parseMarkdown(html);\n const text = fragment.innerText.trim().replace(/\\u200b+/g, '').slice(0, MAX_MESSAGE_LENGTH);\n let textIndex = 0;\n let recursionDeepness = 0;\n const entities: ApiMessageEntity[] = [];\n\n function addEntity(node: ChildNode) {\n const { index, entity } = getEntityDataFromNode(node, text, textIndex);\n\n if (entity) {\n textIndex = index;\n entities.push(entity);\n } else if (node.textContent) {\n textIndex += node.textContent.length;\n }\n\n if (node.hasChildNodes() && recursionDeepness <= MAX_TAG_DEEPNESS) {\n recursionDeepness += 1;\n Array.from(node.childNodes).forEach(addEntity);\n }\n }\n\n Array.from(fragment.childNodes).forEach((node) => {\n recursionDeepness = 1;\n addEntity(node);\n });\n\n return {\n text,\n entities: entities.length ? entities : undefined,\n };\n}\n\nfunction parseMarkdown(html: string) {\n let parsedHtml = html.slice(0);\n\n if (!IS_EMOJI_SUPPORTED) {\n // Emojis\n parsedHtml = parsedHtml.replace(/]+alt=\"([^\"]+)\"[^>]*>/gm, '$1');\n }\n // Strip redundant tags\n parsedHtml = parsedHtml.replace(/<\\/?span([^>]*)?>/g, '');\n\n // Strip redundant nbsp's\n parsedHtml = parsedHtml.replace(/ /g, ' ');\n\n // Replace
with newline\n parsedHtml = parsedHtml.replace(/]*)?>/g, '\\n');\n\n // Strip redundant
tags\n parsedHtml = parsedHtml.replace(/<\\/div>(\\s*)
/g, '\\n');\n parsedHtml = parsedHtml.replace(/
/g, '\\n');\n parsedHtml = parsedHtml.replace(/<\\/div>/g, '');\n\n // Pre\n parsedHtml = parsedHtml.replace(/^`{3}(.*[\\n\\r][^]*?^)`{3}/gm, '
$1
');\n parsedHtml = parsedHtml.replace(/[`]{3}([^`]+)[`]{3}/g, '
$1
');\n\n // Code\n parsedHtml = parsedHtml.replace(/[`]{1}([^`\\n]+)[`]{1}/g, '$1');\n\n // Other simple markdown\n parsedHtml = parsedHtml.replace(/[*]{2}([^*\\n]+)[*]{2}/g, '$1');\n parsedHtml = parsedHtml.replace(/[*]{1}([^*\\n]+)[*]{1}/g, '$1');\n parsedHtml = parsedHtml.replace(/[~]{2}([^~\\n]+)[~]{2}/g, '$1');\n\n return parsedHtml;\n}\n\nfunction getEntityDataFromNode(\n node: ChildNode,\n rawText: string,\n textIndex: number,\n): { index: number; entity?: ApiMessageEntity } {\n const type = getEntityTypeFromNode(node);\n if (!type || !node.textContent) {\n return {\n index: textIndex,\n entity: undefined,\n };\n }\n\n const rawIndex = rawText.indexOf(node.textContent, textIndex);\n // In some cases, last text entity ends with a newline (which gets trimmed from `rawText`).\n // In this case, `rawIndex` would return `-1`, so we use `textIndex` instead.\n const index = rawIndex >= 0 ? rawIndex : textIndex;\n const offset = rawText.substring(0, index).length;\n const { length } = rawText.substring(index, index + node.textContent.length);\n\n let url: string | undefined;\n let userId: number | undefined;\n if (type === ApiMessageEntityTypes.TextUrl) {\n url = (node as HTMLAnchorElement).href;\n }\n if (type === ApiMessageEntityTypes.MentionName) {\n userId = Number((node as HTMLAnchorElement).dataset.userId);\n }\n\n return {\n index,\n entity: {\n type,\n offset,\n length,\n ...(url && { url }),\n ...(userId && { userId }),\n },\n };\n}\n\nfunction getEntityTypeFromNode(node: ChildNode) {\n if (ENTITY_CLASS_BY_NODE_NAME[node.nodeName]) {\n return ENTITY_CLASS_BY_NODE_NAME[node.nodeName];\n }\n\n if (node.nodeName === 'A') {\n const anchor = node as HTMLAnchorElement;\n if (anchor.dataset.entityType === ApiMessageEntityTypes.MentionName) {\n return ApiMessageEntityTypes.MentionName;\n }\n if (anchor.href.startsWith('mailto:')) {\n return ApiMessageEntityTypes.Email;\n }\n if (anchor.href.startsWith('tel:')) {\n return ApiMessageEntityTypes.Phone;\n }\n if (anchor.href !== anchor.textContent) {\n return ApiMessageEntityTypes.TextUrl;\n }\n\n return ApiMessageEntityTypes.Url;\n }\n\n if (node.nodeName === 'SPAN') {\n return (node as HTMLElement).dataset.entityType;\n }\n\n return undefined;\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport './DropTarget.scss';\n\nexport type OwnProps = {\n isQuick?: boolean;\n onFileSelect: (e: React.DragEvent) => void;\n};\n\nconst DropTarget: FC = ({ isQuick, onFileSelect }) => {\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n\n const handleDragEnter = () => { markHovered(); };\n const handleDragLeave = (e: React.DragEvent) => {\n const { relatedTarget: toTarget } = e;\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const className = buildClassName(\n 'DropTarget',\n isHovered && 'hovered',\n );\n\n return (\n \n
\n
\n
Drop files here to send them
\n
{isQuick ? 'in a quick way' : 'without compression'}
\n
\n
\n );\n};\n\nexport default memo(DropTarget);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport DropTarget from './DropTarget';\n\nimport './DropArea.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n withQuick?: boolean;\n onHide: NoneToVoidFunction;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n};\n\nexport enum DropAreaState {\n None = 'none',\n Document = 'document',\n QuickFile = 'quick_file',\n}\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst DropArea: FC = ({\n isOpen, withQuick, onHide, onFileSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef(null);\n const prevWithQuick = usePrevious(withQuick);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onHide) : undefined), [isOpen, onHide]);\n\n const handleFilesDrop = useCallback((e: React.DragEvent) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), false);\n }\n }, [onFileSelect, onHide]);\n\n const handleQuickFilesDrop = useCallback((e: React.DragEvent) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), true);\n }\n }, [onFileSelect, onHide]);\n\n const handleDragLeave = useCallback((e: React.DragEvent) => {\n e.stopPropagation();\n\n const { target: fromTarget, relatedTarget: toTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.DropTarget, .DropArea') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(() => {\n onHide();\n }, DROP_LEAVE_TIMEOUT_MS);\n }\n }, [onHide]);\n\n const handleDragOver = () => {\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n };\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'DropArea',\n transitionClassNames,\n );\n\n return (\n
\n \n {(withQuick || prevWithQuick) && }\n
\n );\n};\n\nexport default memo(DropArea);\n","import { useEffect } from '../lib/teact/teact';\n\nexport default (\n onBlur: AnyToVoidFunction,\n onFocus: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (!document.hasFocus()) {\n onBlur();\n }\n\n window.addEventListener('blur', onBlur);\n window.addEventListener('focus', onFocus);\n\n return () => {\n window.removeEventListener('focus', onFocus);\n window.removeEventListener('blur', onBlur);\n };\n }, [onBlur, onFocus]);\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport { getChatTitle, getUserFirstOrLastName, isChatPrivate } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\n\nimport './PickerSelectedItem.scss';\n\ntype OwnProps = {\n chatOrUserId?: number;\n icon?: string;\n title?: string;\n isMinimized?: boolean;\n canClose?: boolean;\n onClick: (arg: any) => void;\n clickArg: any;\n className?: string;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n user?: ApiUser;\n};\n\nconst PickerSelectedItem: FC = ({\n icon,\n title,\n isMinimized,\n canClose,\n onClick,\n clickArg,\n chat,\n user,\n className,\n}) => {\n useLang();\n\n let iconElement: any;\n let titleText: any;\n\n if (icon && title) {\n iconElement = (\n
\n \n
\n );\n\n titleText = title;\n } else if (chat || user) {\n iconElement = (\n \n );\n\n const name = !chat || (user && !user.isSelf)\n ? getUserFirstOrLastName(user)\n : getChatTitle(chat, user);\n\n titleText = name ? renderText(name) : undefined;\n }\n\n const fullClassName = buildClassName(\n 'PickerSelectedItem',\n className,\n isMinimized && 'minimized',\n canClose && 'closeable',\n );\n\n return (\n onClick(clickArg)}\n title={isMinimized ? titleText : undefined}\n >\n {iconElement}\n {!isMinimized && (\n
\n {titleText}\n
\n )}\n {canClose && (\n
\n \n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n if (!chatOrUserId) {\n return {};\n }\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n return {\n chat,\n user,\n };\n },\n)(PickerSelectedItem));\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nexport default (containerRef: RefObject, isDisabled?: boolean) => {\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n function handleScroll(e: WheelEvent) {\n // Ignore horizontal scroll and let it work natively (e.g. on touchpad)\n if (!e.deltaX) {\n container!.scrollLeft += e.deltaY / 4;\n }\n }\n\n container.addEventListener('wheel', handleScroll, { passive: true });\n\n return () => {\n container.removeEventListener('wheel', handleScroll);\n };\n }, [containerRef, isDisabled]);\n};\n","import { useEffect, useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\n\nimport { ApiMessage } from '../api/types';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (\n chatId: number,\n messageId?: number,\n message?: ApiMessage,\n replyOriginForId?: number,\n) => {\n const { loadMessage } = getDispatch();\n const loadMessageThrottled = useMemo(() => {\n const throttled = throttle(loadMessage, 500, true);\n return () => {\n throttled({ chatId, messageId, replyOriginForId });\n };\n }, [loadMessage, chatId, messageId, replyOriginForId]);\n\n useEffect(() => {\n if (messageId && !message) {\n loadMessageThrottled();\n }\n });\n};\n","import { RefObject } from 'react';\nimport { useState, useEffect, useCallback } from '../lib/teact/teact';\n\nimport { IAnchorPosition } from '../types';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../util/environment';\n\nconst LONG_TAP_DURATION_MS = 250;\nconst SELECTION_ANIMATION_DURATION_MS = 200;\n\nlet contextMenuCounter = 0;\n\nfunction checkIsDisabledForMobile() {\n return IS_MOBILE_SCREEN\n && window.document.body.classList.contains('enable-symbol-menu-transforms');\n}\n\nexport default (\n elementRef: RefObject,\n isMenuDisabled?: boolean,\n) => {\n const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);\n const [contextMenuPosition, setContextMenuPosition] = useState(undefined);\n\n const handleBeforeContextMenu = useCallback((e: React.MouseEvent) => {\n if (!isMenuDisabled && e.button === 2) {\n document.body.classList.add('no-selection');\n }\n }, [isMenuDisabled]);\n\n const handleContextMenu = useCallback((e: React.MouseEvent) => {\n if (isMenuDisabled) {\n return;\n }\n e.preventDefault();\n document.body.classList.remove('no-selection');\n\n if (contextMenuPosition) {\n return;\n }\n document.body.classList.remove('no-selection');\n if (contextMenuCounter === 0) {\n document.body.classList.add('has-context-menu');\n }\n contextMenuCounter++;\n\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: e.clientX, y: e.clientY });\n }, [isMenuDisabled, contextMenuPosition]);\n\n const handleContextMenuClose = useCallback(() => {\n setIsContextMenuOpen(false);\n }, []);\n\n const handleContextMenuHide = useCallback(() => {\n setContextMenuPosition(undefined);\n document.body.classList.remove('no-selection');\n\n setTimeout(() => {\n contextMenuCounter--;\n if (contextMenuCounter === 0) {\n document.body.classList.remove('has-context-menu');\n }\n }, SELECTION_ANIMATION_DURATION_MS);\n }, []);\n\n // Support context menu on touch-devices\n useEffect(() => {\n if (isMenuDisabled || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (!element) {\n return undefined;\n }\n\n let timer: number | undefined;\n\n const clearLongPressTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const emulateContextMenuEvent = (originalEvent: TouchEvent) => {\n clearLongPressTimer();\n\n const { clientX, clientY } = originalEvent.touches[0];\n\n if (contextMenuPosition) {\n return;\n }\n\n // temporarily intercept and clear the next click\n element.addEventListener('touchend', function cancelClickOnce(e) {\n element.removeEventListener('touchend', cancelClickOnce, true);\n e.stopImmediatePropagation();\n e.preventDefault();\n e.stopPropagation();\n }, true);\n\n document.body.classList.add('no-selection');\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: clientX, y: clientY });\n };\n\n const startLongPressTimer = (e: TouchEvent) => {\n if (isMenuDisabled || checkIsDisabledForMobile()) {\n return;\n }\n clearLongPressTimer();\n\n timer = window.setTimeout(() => emulateContextMenuEvent(e), LONG_TAP_DURATION_MS);\n };\n\n // @perf Consider event delegation\n element.addEventListener('touchstart', startLongPressTimer, { passive: true });\n element.addEventListener('touchcancel', clearLongPressTimer, true);\n element.addEventListener('touchend', clearLongPressTimer, true);\n element.addEventListener('touchmove', clearLongPressTimer, { passive: true });\n\n return () => {\n clearLongPressTimer();\n element.removeEventListener('touchstart', startLongPressTimer);\n element.removeEventListener('touchcancel', clearLongPressTimer, true);\n element.removeEventListener('touchend', clearLongPressTimer, true);\n element.removeEventListener('touchmove', clearLongPressTimer);\n };\n }, [contextMenuPosition, isMenuDisabled, elementRef]);\n\n return {\n isContextMenuOpen,\n contextMenuPosition,\n handleBeforeContextMenu,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n };\n};\n","export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import { DEBUG } from '../config';\n\nexport default (mediaEl: HTMLMediaElement) => {\n mediaEl.play().catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n });\n};\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMessageEntity, ApiMessageEntityTypes, ApiMessage } from '../../../api/types';\n\nimport { getMessageText } from '../../../modules/helpers';\nimport renderText from './renderText';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\nexport type TextPart = string | Element;\n\nexport function renderMessageText(message: ApiMessage, highlight?: string, shouldRenderHqEmoji?: boolean) {\n const formattedText = message.content.text;\n\n if (!formattedText || !formattedText.text) {\n const rawText = getMessageText(message);\n return rawText ? [rawText] : undefined;\n }\n const { text, entities } = formattedText;\n\n return renderTextWithEntities(text, entities, highlight, shouldRenderHqEmoji);\n}\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set;\n nestedEntities: IOrganizedEntity[];\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter(Boolean as any);\n\n nestedEntities.forEach((e) => e.organizedIndexes.forEach((i) => organizedIndexes.add(i)));\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntites = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntites.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntites.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n if (!entityText) {\n return renderMessagePart(renderedContent);\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.Blockquote:\n return
{renderMessagePart(renderedContent)}
;\n case ApiMessageEntityTypes.BotCommand:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Code:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.Email:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Italic:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.MentionName:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Mention:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Phone:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Pre:\n return
{renderMessagePart(renderedContent)}
;\n case ApiMessageEntityTypes.Strike:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Underline:\n return {renderMessagePart(renderedContent)};\n default:\n return renderMessagePart(renderedContent);\n }\n}\n\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n if (highlight) {\n return renderText(content, [emojiFilter, 'br', 'highlight'], { highlight });\n } else {\n return renderText(content, [emojiFilter, 'br']);\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent) {\n getDispatch().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent) {\n getDispatch().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getDispatch().searchTextMessagesLocal();\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Italic:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Underline:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Code:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`
${renderedContent}
\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.MentionName:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `${renderedContent}`;\n default:\n return renderedContent;\n }\n}\n","import { useEffect, useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport { imgToCanvas } from '../util/files';\nimport useForceUpdate from './useForceUpdate';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\nconst MAX_CACHE_SIZE = 1000;\n\nconst cache = new Map();\n\nexport default function useBlur(dataUri?: string, isDisabled = false, delay?: number) {\n const blurredRef = useRef(dataUri ? cache.get(dataUri) : undefined);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n if (timeoutRef.current && isDisabled) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useEffect(() => {\n if (!dataUri || blurredRef.current || isDisabled) {\n return;\n }\n\n const img = new Image();\n\n img.onload = () => {\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n const blurredDataUri = canvas.toDataURL();\n\n blurredRef.current = blurredDataUri;\n forceUpdate();\n\n if (cache.size >= MAX_CACHE_SIZE) {\n cache.clear();\n }\n cache.set(dataUri, blurredDataUri);\n };\n\n if (delay) {\n timeoutRef.current = window.setTimeout(() => {\n img.src = dataUri;\n }, delay);\n } else {\n img.src = dataUri;\n }\n }, [dataUri, delay, forceUpdate, isDisabled]);\n\n return blurredRef.current;\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\nimport { fastRaf } from '../util/schedulers';\n\n// Fix for memory leak when unmounting video element\nexport default function useVideoCleanup(videoRef: RefObject, dependencies: any[]) {\n useEffect(() => {\n const videoEl = videoRef.current;\n\n return () => {\n if (videoEl) {\n fastRaf(() => {\n videoEl.pause();\n videoEl.src = '';\n videoEl.load();\n });\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n}\n","import { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl: string) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await navigator.clipboard.write([\n new window.ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useRef, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from './Loading';\nimport Button from './Button';\n\nimport './SearchInput.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n children?: any;\n className?: string;\n inputId?: string;\n value?: string;\n focused?: boolean;\n isLoading?: boolean;\n placeholder?: string;\n disabled?: boolean;\n canClose?: boolean;\n onChange: (value: string) => void;\n onReset?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n onBlur?: NoneToVoidFunction;\n};\n\nconst SearchInput: FC = ({\n ref,\n children,\n value,\n inputId,\n className,\n focused,\n isLoading,\n placeholder,\n disabled,\n canClose,\n onChange,\n onReset,\n onFocus,\n onBlur,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let inputRef = useRef(null);\n if (ref) {\n inputRef = ref;\n }\n\n const [isInputFocused, markInputFocused, unmarkInputFocused] = useFlag(focused);\n\n useEffect(() => {\n if (!inputRef.current) {\n return;\n }\n\n if (focused) {\n inputRef.current.focus();\n } else {\n inputRef.current.blur();\n }\n }, [focused, placeholder]); // Trick for setting focus when selecting a contact to search for\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent) {\n const { currentTarget } = event;\n onChange(currentTarget.value);\n }\n\n function handleFocus() {\n markInputFocused();\n if (onFocus) {\n onFocus();\n }\n }\n\n function handleBlur() {\n unmarkInputFocused();\n if (onBlur) {\n onBlur();\n }\n }\n\n return (\n
\n {children}\n \n \n {isLoading && (\n \n )}\n {!isLoading && (value || canClose) && onReset && (\n \n \n \n )}\n
\n );\n};\n\nexport default memo(SearchInput);\n","import { fastRaf } from './schedulers';\nimport { animate } from './animation';\nimport { IS_IOS } from './environment';\n\nconst DURATION = 450;\n\nexport default function fastSmoothScroll(container: HTMLElement, left: number) {\n // Native way seems to be smoother in Chrome\n if (!IS_IOS) {\n container.scrollTo({ left, behavior: 'smooth' });\n } else {\n fastRaf(() => {\n scrollWithJs(container, left);\n });\n }\n}\n\nfunction scrollWithJs(container: HTMLElement, left: number) {\n const { scrollLeft, offsetWidth: containerWidth, scrollWidth } = container;\n let path = left - scrollLeft;\n\n if (path < 0) {\n const remainingPath = -scrollLeft;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollWidth - (scrollLeft + containerWidth);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollLeft + path;\n const startAt = Date.now();\n\n animate(() => {\n const t = Math.min((Date.now() - startAt) / DURATION, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollLeft = Math.round(target - currentPath);\n\n return t < 1;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { IS_IOS } from './environment';\n\nexport default (container: HTMLDivElement, scrollTop?: number) => {\n if (IS_IOS) {\n container.style.overflow = 'hidden';\n }\n\n if (scrollTop !== undefined) {\n container.scrollTop = scrollTop;\n }\n\n if (IS_IOS) {\n container.style.overflow = '';\n }\n};\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\n\nimport { selectUser } from '../../modules/selectors';\nimport { getUserFirstOrLastName } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\n\nimport './TypingStatus.scss';\n\ntype OwnProps = {\n typingStatus: ApiTypingStatus;\n};\n\ntype StateProps = {\n typingUser?: ApiUser;\n};\n\nconst TypingStatus: FC = ({ typingStatus, typingUser }) => {\n const typingUserName = typingUser && !typingUser.isSelf && getUserFirstOrLastName(typingUser);\n\n return (\n

\n {typingUserName && (\n {renderText(typingUserName)}\n )}\n {typingStatus.action}\n \n

\n );\n};\n\nexport default memo(withGlobal(\n (global, { typingStatus }): StateProps => {\n if (!typingStatus.userId) {\n return {};\n }\n\n const typingUser = selectUser(global, typingStatus.userId);\n\n return { typingUser };\n },\n)(TypingStatus));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n getChatTitle,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './DeleteChatModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n chat: ApiChat;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isChatWithSelf?: boolean;\n isPrivateChat: boolean;\n isBasicGroup: boolean;\n isSuperGroup: boolean;\n canDeleteForAll?: boolean;\n chatTitle: string;\n contactName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteChatModal: FC = ({\n isOpen,\n chat,\n isChannel,\n isPrivateChat,\n isChatWithSelf,\n isBasicGroup,\n isSuperGroup,\n canDeleteForAll,\n chatTitle,\n contactName,\n onClose,\n leaveChannel,\n deleteHistory,\n deleteChannel,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: true });\n onClose();\n }, [deleteHistory, chat.id, chat.lastMessage, onClose]);\n\n const handleDeleteChat = useCallback(() => {\n if (isPrivateChat || isBasicGroup) {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: false });\n } else if ((isChannel || isSuperGroup) && !chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else if ((isChannel || isSuperGroup) && chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n }\n onClose();\n }, [\n isPrivateChat,\n isBasicGroup,\n isChannel,\n isSuperGroup,\n chat.isCreator,\n chat.lastMessage,\n chat.id,\n onClose,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n ]);\n\n const lang = useLang();\n\n function renderHeader() {\n return (\n
\n \n

{renderTitle()}

\n
\n );\n }\n\n function renderTitle() {\n if (isChannel && !chat.isCreator) {\n return 'Leave Channel?';\n }\n\n if (isChannel && chat.isCreator) {\n return 'Delete and Leave Channel?';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Leave Group?';\n }\n\n return 'Delete Chat?';\n }\n\n function renderMessage() {\n if (isChannel && !chat.isCreator) {\n return

Are you sure you want to leave channel {chatTitle}?

;\n }\n if (isChannel && chat.isCreator) {\n return

Are you sure you want to delete and leave channel {chatTitle}?

;\n }\n\n if (isBasicGroup || isSuperGroup) {\n return

Are you sure you want to leave group {chatTitle}?

;\n }\n\n return

Are you sure you want to delete chat with {contactName}?

;\n }\n\n function renderActionText() {\n if (isChannel && !chat.isCreator) {\n return 'Leave Channel';\n }\n if (isChannel && chat.isCreator) {\n return 'Delete and Leave Channel';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Leave Group';\n }\n\n return `Delete${canDeleteForAll ? ' just for me' : ''}`;\n }\n\n return (\n \n {renderMessage()}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chat }): StateProps => {\n const isPrivateChat = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, chat.id);\n const canDeleteForAll = (isPrivateChat && !isChatWithSelf);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel: isChatChannel(chat),\n isBasicGroup: isChatBasicGroup(chat),\n isSuperGroup: isChatSuperGroup(chat),\n canDeleteForAll,\n chatTitle: getChatTitle(chat),\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['leaveChannel', 'deleteHistory', 'deleteChannel']),\n)(DeleteChatModal));\n","/*\n * Thanks to Ace Monkey for this mind-blowing patch.\n */\n\nexport function patchSafariProgressiveAudio(audioEl: HTMLAudioElement) {\n if (audioEl.dataset.patchedForSafari) {\n return;\n }\n\n audioEl.addEventListener('play', () => {\n const t = audioEl.currentTime;\n\n function onProgress() {\n if (!audioEl.buffered.length) {\n return;\n }\n\n audioEl.dataset.patchForSafariInProgress = 'true';\n audioEl.currentTime = audioEl.duration - 1;\n audioEl.addEventListener('progress', () => {\n delete audioEl.dataset.patchForSafariInProgress;\n audioEl.currentTime = t;\n if (audioEl.paused) {\n audioEl.play();\n }\n }, { once: true });\n\n audioEl.removeEventListener('progress', onProgress);\n }\n\n audioEl.addEventListener('progress', onProgress);\n }, { once: true });\n\n audioEl.dataset.patchedForSafari = 'true';\n}\n\nexport function isSafariPatchInProgress(audioEl: HTMLAudioElement) {\n return Boolean(audioEl.dataset.patchForSafariInProgress);\n}\n","import { useLayoutEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useLayoutEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import React, {\n FC, useCallback, useEffect, useState, memo, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getDocumentExtension, getDocumentHasPreview } from './helpers/documentInfo';\nimport { getMediaTransferState, getMessageMediaHash, getMessageMediaThumbDataUri } from '../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../hooks/useMedia';\nimport download from '../../util/download';\n\nimport File from './File';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n smaller?: boolean;\n isSelected?: boolean;\n isSelectable?: boolean;\n uploadProgress?: number;\n withDate?: boolean;\n datetime?: number;\n className?: string;\n sender?: string;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Document: FC = ({\n message,\n observeIntersection,\n smaller,\n uploadProgress,\n withDate,\n datetime,\n className,\n sender,\n isSelected,\n isSelectable,\n onCancelUpload,\n onDateClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const document = message.content.document!;\n const extension = getDocumentExtension(document) || '';\n const { fileName, size, timestamp } = document;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, 'download'), !isDownloadAllowed);\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isDownloadAllowed);\n\n const hasPreview = getDocumentHasPreview(document);\n const thumbDataUri = hasPreview ? getMessageMediaThumbDataUri(message) : undefined;\n const localBlobUrl = hasPreview ? document.previewBlobUrl : undefined;\n const previewData = useMedia(getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [isUploading, onCancelUpload]);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n useEffect(() => {\n if (isDownloadAllowed && mediaData) {\n download(mediaData, fileName);\n setIsDownloadAllowed(false);\n }\n }, [fileName, mediaData, isDownloadAllowed]);\n\n return (\n \n );\n};\n\nexport default memo(Document);\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './StickerSetModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst StickerSetModalAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerSetModal = useModuleLoader(Bundles.Extra, 'StickerSetModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSetModal ? : undefined;\n};\n\nexport default StickerSetModalAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IAnchorPosition } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useVirtualBackdrop from '../../../hooks/useVirtualBackdrop';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './TextFormatter.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n anchorPosition?: IAnchorPosition;\n selectedRange?: Range;\n onClose: () => void;\n};\n\ninterface ISelectedTextFormats {\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strikethrough?: boolean;\n monospace?: boolean;\n}\n\nconst TEXT_FORMAT_BY_TAG_NAME: Record = {\n B: 'bold',\n STRONG: 'bold',\n I: 'italic',\n EM: 'italic',\n U: 'underline',\n DEL: 'strikethrough',\n CODE: 'monospace',\n};\n\nconst TextFormatter: FC = ({\n isOpen,\n anchorPosition,\n selectedRange,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const linkUrlInputRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n const [isLinkControlOpen, openLinkControl, closeLinkControl] = useFlag();\n const [linkUrl, setLinkUrl] = useState('');\n const [isEditingLink, setIsEditingLink] = useState(false);\n const [inputClassName, setInputClassName] = useState();\n const [selectedTextFormats, setSelectedTextFormats] = useState({});\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n useVirtualBackdrop(\n isOpen,\n containerRef,\n onClose,\n );\n\n useEffect(() => {\n if (isLinkControlOpen) {\n linkUrlInputRef.current!.focus();\n } else {\n setLinkUrl('');\n setIsEditingLink(false);\n }\n }, [isLinkControlOpen]);\n\n useEffect(() => {\n if (!shouldRender) {\n closeLinkControl();\n setSelectedTextFormats({});\n setInputClassName(undefined);\n }\n }, [closeLinkControl, shouldRender]);\n\n useEffect(() => {\n if (!isOpen || !selectedRange) {\n return;\n }\n\n const selectedFormats: ISelectedTextFormats = {};\n let { parentElement } = selectedRange.commonAncestorContainer;\n while (parentElement && parentElement.id !== EDITABLE_INPUT_ID) {\n const textFormat = TEXT_FORMAT_BY_TAG_NAME[parentElement.tagName];\n if (textFormat) {\n selectedFormats[textFormat] = true;\n }\n\n parentElement = parentElement.parentElement;\n }\n\n setSelectedTextFormats(selectedFormats);\n }, [isOpen, selectedRange, openLinkControl]);\n\n function restoreSelection() {\n if (!selectedRange) {\n return;\n }\n\n const selection = window.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(selectedRange);\n }\n }\n\n const getSelectedText = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.toString();\n }, [selectedRange]);\n\n const getSelectedElement = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.commonAncestorContainer.parentElement;\n }, [selectedRange]);\n\n function updateInputStyles() {\n const input = linkUrlInputRef.current;\n if (!input) {\n return;\n }\n\n const { offsetWidth, scrollWidth, scrollLeft } = input;\n if (scrollWidth <= offsetWidth) {\n setInputClassName(undefined);\n return;\n }\n\n let className = '';\n if (scrollLeft < scrollWidth - offsetWidth) {\n className = 'mask-right';\n }\n if (scrollLeft > 0) {\n className += ' mask-left';\n }\n\n setInputClassName(className);\n }\n\n function handleLinkUrlChange(e: React.ChangeEvent) {\n setLinkUrl(e.target.value);\n updateInputStyles();\n }\n\n function getFormatButtonClassName(key: keyof ISelectedTextFormats) {\n if (selectedTextFormats[key]) {\n return 'active';\n }\n\n if (key === 'monospace' || key === 'strikethrough') {\n if (Object.keys(selectedTextFormats).some(\n (fKey) => fKey !== key && !!selectedTextFormats[fKey as keyof ISelectedTextFormats],\n )) {\n return 'disabled';\n }\n } else if (selectedTextFormats.monospace || selectedTextFormats.strikethrough) {\n return 'disabled';\n }\n\n return undefined;\n }\n\n const handleBoldText = useCallback(() => {\n setSelectedTextFormats((selectedFormats) => {\n // Somehow re-applying 'bold' command to already bold text doesn't work\n document.execCommand(selectedFormats.bold ? 'removeFormat' : 'bold');\n Object.keys(selectedFormats).forEach((key) => {\n if ((key === 'italic' || key === 'underline') && !!selectedFormats[key]) {\n document.execCommand(key);\n }\n });\n\n return {\n ...selectedFormats,\n bold: !selectedFormats.bold,\n };\n });\n }, []);\n\n const handleItalicText = useCallback(() => {\n document.execCommand('italic');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n italic: !selectedFormats.italic,\n }));\n }, []);\n\n const handleUnderlineText = useCallback(() => {\n document.execCommand('underline');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n underline: !selectedFormats.underline,\n }));\n }, []);\n\n const handleStrikethroughText = useCallback(() => {\n if (selectedTextFormats.strikethrough) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'DEL'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n strikethrough: false,\n }));\n\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.strikethrough,\n ]);\n\n const handleMonospaceText = useCallback(() => {\n if (selectedTextFormats.monospace) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'CODE'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n monospace: false,\n }));\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.monospace,\n ]);\n\n function handleLinkUrlConfirm() {\n const formattedLinkUrl = linkUrl.includes('://') ? linkUrl : `http://${linkUrl}`;\n\n if (isEditingLink) {\n const element = getSelectedElement();\n if (!element || element.tagName !== 'A') {\n return;\n }\n\n (element as HTMLAnchorElement).href = formattedLinkUrl;\n\n onClose();\n return;\n }\n\n const text = getSelectedText();\n restoreSelection();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n const HANDLERS_BY_KEY_CODE: Record = {\n KeyK: openLinkControl,\n KeyB: handleBoldText,\n KeyU: handleUnderlineText,\n KeyI: handleItalicText,\n KeyM: handleMonospaceText,\n KeyS: handleStrikethroughText,\n };\n\n const handler = HANDLERS_BY_KEY_CODE[e.code];\n\n if (\n e.altKey\n || !(e.ctrlKey || e.metaKey)\n || !handler\n ) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n handler();\n }, [\n handleBoldText, handleItalicText, handleUnderlineText,\n handleMonospaceText, handleStrikethroughText,\n openLinkControl,\n ]);\n\n useEffect(() => {\n if (isOpen) {\n document.addEventListener('keydown', handleKeyDown);\n }\n\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [isOpen, handleKeyDown]);\n\n const lang = useLang();\n\n function handleContainerKeyDown(e: React.KeyboardEvent) {\n if (e.key === 'Enter' && isLinkControlOpen) {\n handleLinkUrlConfirm();\n e.preventDefault();\n }\n }\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'TextFormatter',\n transitionClassNames,\n isLinkControlOpen && 'link-control-shown',\n );\n\n const linkUrlConfirmClassName = buildClassName(\n 'TextFormatter-link-url-confirm',\n !!linkUrl.length && 'shown',\n );\n\n const style = anchorPosition\n ? `left: ${anchorPosition.x}px; top: ${anchorPosition.y}px;--text-formatter-left: ${anchorPosition.x}px;`\n : '';\n\n return (\n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n\n
\n
\n \n
\n\n \n \n
\n\n
\n
\n \n \n \n
\n
\n
\n
\n );\n};\n\nexport default memo(TextFormatter);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport {\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n} from '../../modules/helpers';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\n\nimport './Media.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n idPrefix?: string;\n onClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Media: FC = ({ message, idPrefix = 'shared-media', onClick }) => {\n const handleClick = useCallback(() => {\n onClick!(message.id, message.chatId);\n }, [message.id, message.chatId, onClick]);\n\n const thumbDataUri = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(mediaBlobUrl, 'slow');\n\n const video = getMessageVideo(message);\n\n return (\n
\n {shouldRenderThumb && (\n \"\"\n )}\n {shouldRenderFullMedia && (\n \"\"\n )}\n {video && {video.isGif ? 'GIF' : formatMediaDuration(video.duration)}}\n
\n );\n};\n\nexport default memo(Media);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiAudio, ApiMessage, ApiVoice,\n} from '../../api/types';\nimport { ISettings } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDateTime, formatMediaDuration, formatPastTimeShort } from '../../util/dateFormat';\nimport {\n getMediaDuration,\n getMediaTransferState,\n getMessageKey,\n getMessageMediaFormat,\n getMessageMediaHash,\n isMessageLocal,\n isOwnMessage,\n} from '../../modules/helpers';\nimport { renderWaveformToDataUri } from './helpers/waveform';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport { decodeWaveform, interpolateArray } from '../../util/waveform';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './Audio.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n uploadProgress?: number;\n renderingFor?: 'searchResult' | 'sharedMedia';\n date?: number;\n lastSyncTime?: number;\n className?: string;\n isSelectable?: boolean;\n isSelected?: boolean;\n onPlay: (messageId: number, chatId: number) => void;\n onReadMedia?: () => void;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n};\n\ninterface ISeekMethods {\n handleStartSeek: (e: React.MouseEvent) => void;\n handleSeek: (e: React.MouseEvent) => void;\n handleStopSeek: () => void;\n}\n\nconst AVG_VOICE_DURATION = 30;\nconst MIN_SPIKES = IS_MOBILE_SCREEN ? 20 : 25;\nconst MAX_SPIKES = IS_MOBILE_SCREEN ? 50 : 75;\n// This is needed for browsers requiring user interaction before playing.\nconst PRELOAD = true;\n\nconst Audio: FC = ({\n theme,\n message,\n senderTitle,\n uploadProgress,\n renderingFor,\n date,\n lastSyncTime,\n className,\n isSelectable,\n isSelected,\n onPlay,\n onReadMedia,\n onCancelUpload,\n onDateClick,\n}) => {\n const { content: { audio, voice }, isMediaUnread } = message;\n const isVoice = Boolean(voice);\n const isSeeking = useRef(false);\n\n const [isActivated, setIsActivated] = useState(false);\n const shouldDownload = (isActivated || PRELOAD) && lastSyncTime;\n\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n );\n\n function handleForcePlay() {\n setIsActivated(true);\n onPlay(message.id, message.chatId);\n }\n\n const {\n isBuffered, bufferedProgress, bufferingHandlers, checkBuffering,\n } = useBuffering();\n\n const {\n isPlaying, playProgress, playPause, setCurrentTime, duration,\n } = useAudioPlayer(\n getMessageKey(message),\n getMediaDuration(message)!,\n mediaData,\n bufferingHandlers,\n checkBuffering,\n isActivated,\n handleForcePlay,\n isMessageLocal(message),\n );\n\n useEffect(() => {\n setIsActivated(isPlaying);\n }, [isPlaying]);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isActivated && !isBuffered);\n\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring);\n\n const handleButtonClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n\n return;\n }\n\n if (!isPlaying) {\n onPlay(message.id, message.chatId);\n }\n\n setIsActivated(!isActivated);\n playPause();\n }, [isPlaying, isUploading, message.id, message.chatId, onCancelUpload, onPlay, playPause, isActivated]);\n\n useEffect(() => {\n if (isPlaying && onReadMedia && isMediaUnread) {\n onReadMedia();\n }\n }, [isPlaying, isMediaUnread, onReadMedia]);\n\n const handleSeek = useCallback((e: React.MouseEvent) => {\n if (isSeeking.current) {\n const seekBar = e.currentTarget.closest('.seekline,.waveform');\n if (seekBar) {\n const { width, left } = seekBar.getBoundingClientRect();\n setCurrentTime(duration * ((e.clientX - left) / width));\n }\n }\n }, [duration, setCurrentTime]);\n\n const handleStartSeek = useCallback((e: React.MouseEvent) => {\n isSeeking.current = true;\n handleSeek(e);\n }, [handleSeek]);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n }, []);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n useLang();\n\n function getFirstLine() {\n if (isVoice) {\n return senderTitle || 'Voice';\n }\n\n const { title, fileName } = audio!;\n\n return title || fileName;\n }\n\n function getSecondLine() {\n if (isVoice) {\n return formatMediaDuration(voice!.duration);\n }\n\n const { performer } = audio!;\n\n return (\n <>\n {performer && renderText(performer)}\n {performer && senderTitle && }\n {senderTitle && renderText(senderTitle)}\n \n );\n }\n\n const seekHandlers = { handleStartSeek, handleSeek, handleStopSeek };\n const isOwn = isOwnMessage(message);\n const renderedWaveform = useMemo(\n () => voice && renderWaveform(voice, playProgress, isOwn, seekHandlers, theme),\n [voice, playProgress, isOwn, seekHandlers, theme],\n );\n\n const fullClassName = buildClassName(\n 'Audio media-inner',\n className,\n isOwn && !renderingFor && 'own',\n renderingFor && 'bigger',\n isSelected && 'audio-is-selected',\n );\n\n const buttonClassNames = ['toggle-play'];\n if (shouldRenderSpinner) {\n buttonClassNames.push('loading');\n } else if (isPlaying) {\n buttonClassNames.push('pause');\n } else if (!isPlaying) {\n buttonClassNames.push('play');\n }\n\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n const contentClassName = buildClassName('content', showSeekline && 'with-seekline');\n\n function renderSearchResult() {\n return (\n <>\n
\n
\n

{renderText(getFirstLine())}

\n\n
\n {date && (\n \n {formatPastTimeShort(date * 1000)}\n \n )}\n
\n
\n\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n

\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {getSecondLine()}\n

\n )}\n
\n \n );\n }\n\n return (\n
\n {isSelectable && (\n
\n {isSelected && }\n
\n )}\n \n \n \n \n {shouldRenderSpinner && (\n
\n \n
\n )}\n {renderingFor === 'searchResult' && renderSearchResult()}\n {renderingFor !== 'searchResult' && audio && renderAudio(\n audio, isPlaying, playProgress, bufferedProgress, seekHandlers, date,\n onDateClick ? handleDateClick : undefined,\n )}\n {renderingFor !== 'searchResult' && voice && renderVoice(voice, renderedWaveform, isMediaUnread)}\n
\n );\n};\n\nfunction renderAudio(\n audio: ApiAudio,\n isPlaying: boolean,\n playProgress: number,\n bufferedProgress: number,\n seekHandlers: ISeekMethods,\n date?: number,\n handleDateClick?: () => void,\n) {\n const {\n title, performer, duration, fileName,\n } = audio;\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n\n return (\n
\n

{renderText(title || fileName)}

\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n
\n {renderText(performer || 'Unknown')}\n {date && (\n <>\n {' '}\n •\n {' '}\n {formatMediaDateTime(date * 1000)}\n \n )}\n
\n )}\n

\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {formatMediaDuration(duration)}\n

\n
\n );\n}\n\nfunction renderVoice(voice: ApiVoice, renderedWaveform: any, isMediaUnread?: boolean) {\n return (\n
\n {renderedWaveform}\n

\n {formatMediaDuration(voice.duration)}\n {isMediaUnread && }\n

\n
\n );\n}\n\nfunction renderWaveform(\n voice: ApiVoice,\n playProgress = 0,\n isOwn = false,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n theme: ISettings['theme'],\n) {\n const { waveform, duration } = voice;\n\n if (!waveform) {\n return undefined;\n }\n\n const fillColor = theme === 'dark' ? '#494B75' : '#CBCBCB';\n const fillOwnColor = theme === 'dark' ? '#C69C85' : '#B0DEA6';\n const progressFillColor = theme === 'dark' ? '#868DF5' : '#54a3e6';\n const progressFillOwnColor = theme === 'dark' ? '#FFFFFF' : '#53ad53';\n const durationFactor = Math.min(duration / AVG_VOICE_DURATION, 1);\n const spikesCount = Math.round(MIN_SPIKES + (MAX_SPIKES - MIN_SPIKES) * durationFactor);\n const decodedWaveform = decodeWaveform(new Uint8Array(waveform));\n const { data: spikes, peak } = interpolateArray(decodedWaveform, spikesCount);\n const { src, width, height } = renderWaveformToDataUri(spikes, playProgress, {\n peak,\n fillStyle: isOwn ? fillOwnColor : fillColor,\n progressFillStyle: isOwn ? progressFillOwnColor : progressFillColor,\n });\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n \n );\n}\n\nfunction renderSeekline(\n playProgress: number,\n bufferedProgress: number,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n) {\n return (\n \n \n \n \n \n \n \n \n \n \n
\n );\n}\n\nexport default memo(withGlobal((global) => ({ theme: global.settings.byKey.theme }))(Audio));\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","type IWaveformProps = {\n peak: number;\n fillStyle: string;\n progressFillStyle: string;\n};\n\nconst SPIKE_WIDTH = 2;\nconst SPIKE_STEP = 4;\nconst SPIKE_RADIUS = 1;\nconst HEIGHT = 23;\n\nexport function renderWaveformToDataUri(\n spikes: number[],\n progress: number,\n {\n peak, fillStyle, progressFillStyle,\n }: IWaveformProps,\n) {\n const width = spikes.length * SPIKE_STEP;\n const height = HEIGHT;\n\n const canvas = document.createElement('canvas');\n canvas.width = width * 2;\n canvas.height = height * 2;\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d')!;\n ctx.scale(2, 2);\n\n spikes.forEach((item, i) => {\n ctx.globalAlpha = (i / spikes.length >= progress) ? 0.5 : 1;\n ctx.fillStyle = progress > i / spikes.length ? progressFillStyle : fillStyle;\n const spikeHeight = Math.max(2, HEIGHT * (item / Math.max(1, peak)));\n roundedRectangle(ctx, i * SPIKE_STEP, height, SPIKE_WIDTH, spikeHeight, SPIKE_RADIUS);\n ctx.fill();\n });\n\n return {\n src: canvas.toDataURL(),\n width,\n height,\n };\n}\n\nfunction roundedRectangle(\n ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number,\n) {\n if (width < 2 * radius) {\n radius = width / 2;\n }\n if (height < 2 * radius) {\n radius = height / 2;\n }\n\n ctx.beginPath();\n ctx.moveTo(x + radius, y);\n ctx.arcTo(x + width, y, x + width, y - height, radius);\n ctx.arcTo(x + width, y - height, x, y - height, radius);\n ctx.arcTo(x, y - height, x, y, radius);\n ctx.arcTo(x, y, x + width, y, radius);\n ctx.closePath();\n}\n","import React, {\n FC, useLayoutEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Tab.scss';\n\ntype OwnProps = {\n className?: string;\n title: string;\n active?: boolean;\n badgeCount?: number;\n isBadgeActive?: boolean;\n previousActiveTab?: number;\n onClick: (arg: number) => void;\n clickArg: number;\n};\n\nconst Tab: FC = ({\n className,\n title,\n active,\n badgeCount,\n isBadgeActive,\n previousActiveTab,\n onClick,\n clickArg,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const tabRef = useRef(null);\n\n useLayoutEffect(() => {\n if (!active || previousActiveTab === undefined) {\n return;\n }\n\n const tab = tabRef.current!;\n const indicator = tab.querySelector('i')!;\n const currentIndicator = tab.parentElement!.children[previousActiveTab].querySelector('i')!;\n\n currentIndicator.classList.remove('animate');\n indicator.classList.remove('animate');\n\n // We move and resize our indicator so it repeats the position and size of the previous one.\n const shiftLeft = currentIndicator.parentElement!.offsetLeft - indicator.parentElement!.offsetLeft;\n const scaleFactor = currentIndicator.clientWidth / indicator.clientWidth;\n indicator.style.transform = `translate3d(${shiftLeft}px, 0, 0) scale3d(${scaleFactor}, 1, 1)`;\n\n // 3 AFs needed here to synchronize animations with Transition component\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Now we remove the transform to let it animate to its own position and size.\n indicator.classList.add('animate');\n indicator.style.transform = 'none';\n });\n });\n });\n }, [active, previousActiveTab]);\n\n return (\n onClick(clickArg)}\n ref={tabRef}\n >\n \n {title}\n {!!badgeCount && (\n {badgeCount}\n )}\n \n \n \n );\n};\n\nexport default memo(Tab);\n","import React, {\n FC, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport fastSmoothScrollHorizontal from '../../util/fastSmoothScrollHorizontal';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHorizontalScroll from '../../hooks/useHorizontalScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Tab from './Tab';\n\nimport './TabList.scss';\n\nexport type TabWithProperties = {\n title: string;\n badgeCount?: number;\n isBadgeActive?: boolean;\n};\n\ntype OwnProps = {\n tabs: readonly TabWithProperties[];\n activeTab: number;\n onSwitchTab: (index: number) => void;\n};\n\nconst TAB_SCROLL_THRESHOLD_PX = 16;\n\nconst TabList: FC = ({ tabs, activeTab, onSwitchTab }) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const previousActiveTab = usePrevious(activeTab);\n\n useHorizontalScroll(containerRef);\n\n // Scroll container to place active tab in the center\n useEffect(() => {\n const container = containerRef.current!;\n if (container.scrollWidth <= container.offsetWidth) {\n return;\n }\n\n const activeTabElement = container.querySelector('.Tab.active') as HTMLElement | null;\n if (activeTabElement) {\n const newLeft = activeTabElement.offsetLeft - (container.offsetWidth / 2) + (activeTabElement.offsetWidth / 2);\n\n // Prevent scrolling by only a couple of pixels, which doesn't look smooth\n if (Math.abs(newLeft - container.scrollLeft) < TAB_SCROLL_THRESHOLD_PX) {\n return;\n }\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n }, [activeTab]);\n\n const lang = useLang();\n\n return (\n
\n {tabs.map((tab, i) => (\n \n ))}\n
\n );\n};\n\nexport default memo(TabList);\n","import { ApiError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding key.',\n // eslint-disable-next-line max-len\n CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n","import { useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { ApiChat, ApiUser } from '../api/types';\nimport { isChatArchived, getCanDeleteChat, isChatPrivate } from '../modules/helpers';\n\nexport default ({\n chat,\n privateChatUser,\n handleDelete,\n folderId,\n isPinned,\n}: {\n chat: ApiChat | undefined;\n privateChatUser: ApiUser | undefined;\n handleDelete: () => void;\n folderId?: number;\n isPinned?: boolean;\n}) => {\n const {\n toggleChatPinned,\n updateChatMutedState,\n toggleChatArchived,\n toggleChatUnread,\n } = getDispatch();\n\n return useMemo(() => {\n if (!chat) {\n return undefined;\n }\n\n const isChatWithSelf = privateChatUser && privateChatUser.isSelf;\n\n const actionUnreadMark = chat.unreadCount || chat.hasUnreadMark\n ? { title: 'Mark as Read', icon: 'readchats', handler: () => toggleChatUnread({ id: chat.id }) }\n : { title: 'Mark as Unread', icon: 'unread', handler: () => toggleChatUnread({ id: chat.id }) };\n\n const actionPin = isPinned\n ? { title: 'Unpin', icon: 'unpin', handler: () => toggleChatPinned({ id: chat.id, folderId }) }\n : { title: 'Pin', icon: 'pin', handler: () => toggleChatPinned({ id: chat.id, folderId }) };\n\n const actionMute = chat.isMuted\n ? { title: 'Unmute', icon: 'unmute', handler: () => updateChatMutedState({ chatId: chat.id, isMuted: false }) }\n : { title: 'Mute', icon: 'mute', handler: () => updateChatMutedState({ chatId: chat.id, isMuted: true }) };\n\n const actionArchive = isChatArchived(chat)\n ? { title: 'Unarchive', icon: 'unarchive', handler: () => toggleChatArchived({ id: chat.id }) }\n : { title: 'Archive', icon: 'archive', handler: () => toggleChatArchived({ id: chat.id }) };\n\n const actionDelete = {\n title: isChatPrivate(chat.id) ? 'Delete' : (getCanDeleteChat(chat) ? 'Delete and Leave' : 'Leave'),\n icon: 'delete',\n destructive: true,\n handler: handleDelete,\n };\n\n return [\n actionUnreadMark,\n actionPin,\n ...(!isChatWithSelf ? [\n actionMute,\n actionArchive,\n ] : []),\n actionDelete,\n ];\n }, [\n chat, privateChatUser, handleDelete, folderId, isPinned,\n toggleChatPinned, updateChatMutedState, toggleChatArchived, toggleChatUnread,\n ]);\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../api/types';\nimport { formatPastTimeShort } from '../../util/dateFormat';\nimport MessageOutgoingStatus from './MessageOutgoingStatus';\nimport './LastMessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n};\n\nconst LastMessageMeta: FC = ({ message, outgoingStatus }) => {\n return (\n
\n {outgoingStatus && (\n \n )}\n {formatPastTimeShort(message.date * 1000)}\n
\n );\n};\n\nexport default LastMessageMeta;\n","import React, { FC } from '../../lib/teact/teact';\n\nimport { ApiMessageOutgoingStatus } from '../../api/types';\n\nimport Transition from '../ui/Transition';\n\nimport './MessageOutgoingStatus.scss';\n\ntype OwnProps = {\n status: ApiMessageOutgoingStatus;\n};\n\nenum Keys {\n failed, pending, succeeded, read,\n}\n\nconst MessageOutgoingStatus: FC = ({ status }) => {\n return (\n
\n \n {() => (\n \n )}\n \n
\n );\n};\n\nexport default MessageOutgoingStatus;\n","import { useState, useEffect } from '../lib/teact/teact';\nimport { IAnchorPosition } from '../types';\n\nexport default (\n anchor: IAnchorPosition | undefined,\n getTriggerElement: () => HTMLElement | null,\n getRootElement: () => HTMLElement | null,\n getMenuElement: () => HTMLElement | null,\n extraPaddingX = 0,\n extraTopPadding = 0,\n) => {\n const [positionX, setPositionX] = useState<'right' | 'left'>('right');\n const [positionY, setPositionY] = useState<'top' | 'bottom'>('bottom');\n const [style, setStyle] = useState('');\n\n useEffect(() => {\n const triggerEl = getTriggerElement();\n if (!anchor || !triggerEl) {\n return;\n }\n\n let { x, y } = anchor;\n const emptyRect = {\n width: 0, left: 0, height: 0, top: 0,\n };\n\n const menuEl = getMenuElement();\n const rootEl = getRootElement();\n\n const triggerRect = triggerEl.getBoundingClientRect();\n const menuRect = menuEl ? { width: menuEl.offsetWidth, height: menuEl.offsetHeight } : emptyRect;\n const rootRect = rootEl ? rootEl.getBoundingClientRect() : emptyRect;\n\n if (x + menuRect.width + extraPaddingX < rootRect.width + rootRect.left) {\n setPositionX('left');\n x += 3;\n } else if (x - menuRect.width > 0) {\n setPositionX('right');\n x -= 3;\n } else {\n setPositionX('left');\n x = 16;\n }\n\n if (y + menuRect.height < rootRect.height + rootRect.top) {\n setPositionY('top');\n } else {\n setPositionY('bottom');\n\n if (y - menuRect.height < rootRect.top + extraTopPadding) {\n y = rootRect.top + extraTopPadding + menuRect.height;\n }\n }\n\n setStyle(`left: ${x - triggerRect.left}px; top: ${y - triggerRect.top}px;`);\n }, [\n anchor, extraPaddingX, extraTopPadding,\n getMenuElement, getRootElement, getTriggerElement,\n ]);\n\n return {\n positionX,\n positionY,\n style,\n };\n};\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\n\ntype ChildrenFn = () => any;\n\ntype OwnProps = {\n isOpen: boolean;\n isCustom?: boolean;\n id?: string;\n className?: string;\n onClick?: (e: React.MouseEvent) => void;\n children: ChildrenFn;\n};\n\nconst ShowTransition: FC = ({\n isOpen, isCustom, id, className, onClick, children,\n}) => {\n const { shouldRender, transitionClassNames } = useShowTransition(\n isOpen, undefined, undefined, isCustom ? false : undefined,\n );\n const prevIsOpen = usePrevious(isOpen);\n const prevChildren = usePrevious(children);\n const fromChildrenRef = useRef();\n\n if (prevIsOpen && !isOpen) {\n fromChildrenRef.current = prevChildren;\n }\n\n return (\n shouldRender && (\n
\n {isOpen ? children() : fromChildrenRef.current!()}\n
\n )\n );\n};\n\nexport default ShowTransition;\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { register } from '../util/audioPlayer';\nimport useEffectWithPrevDeps from './useEffectWithPrevDeps';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\nimport useOnChange from './useOnChange';\n\ntype Handler = (e: Event) => void;\n\nexport default (\n trackId: string,\n originalDuration: number, // Sometimes incorrect for voice messages\n src?: string,\n handlers?: Record,\n onInit?: (element: HTMLAudioElement) => void,\n shouldPlay = false,\n onForcePlay?: NoneToVoidFunction,\n noPlaylist = false,\n) => {\n // eslint-disable-next-line no-null/no-null\n const controllerRef = useRef>(null);\n\n const [isPlaying, setIsPlaying] = useState(false);\n let isPlayingSync = isPlaying;\n\n const [playProgress, setPlayProgress] = useState(0);\n\n useOnChange(() => {\n controllerRef.current = register(trackId, (eventName, e) => {\n switch (eventName) {\n case 'onPlay':\n setIsPlaying(true);\n break;\n case 'onPause':\n setIsPlaying(false);\n break;\n case 'onTimeUpdate': {\n const { proxy } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n setPlayProgress(proxy.currentTime / duration);\n break;\n }\n }\n\n if (handlers && handlers[eventName]) {\n handlers[eventName](e);\n }\n }, onForcePlay);\n\n const { proxy } = controllerRef.current!;\n\n if (!isPlaying && !proxy.paused) {\n setIsPlaying(true);\n isPlayingSync = true;\n }\n\n if (onInit) {\n onInit(proxy);\n }\n }, [trackId]);\n\n const {\n play, pause, setCurrentTime, proxy, destroy,\n } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n\n // RAF progress\n useEffect(() => {\n if (duration && !isSafariPatchInProgress(proxy)) {\n setPlayProgress(proxy.currentTime / duration);\n }\n }, [duration, playProgress, proxy]);\n\n // Cleanup\n useEffect(() => () => {\n destroy(noPlaylist);\n }, [destroy, noPlaylist]);\n\n // Autoplay once `src` is present\n useEffectWithPrevDeps(([prevShouldPlay, prevSrc]) => {\n if (prevShouldPlay === shouldPlay && src === prevSrc) {\n return;\n }\n\n // When paused by another player\n if (proxy.src && proxy.paused) {\n return;\n }\n\n if (shouldPlay && src && !isPlaying) {\n play(src);\n }\n }, [shouldPlay, src, isPlaying, play, proxy.src, proxy.paused]);\n\n const playPause = useCallback(() => {\n if (isPlaying) {\n pause();\n } else if (src) {\n play(src);\n }\n }, [src, pause, play, isPlaying]);\n\n return {\n isPlaying: isPlayingSync,\n playProgress,\n playPause,\n setCurrentTime,\n audioProxy: proxy,\n duration,\n };\n};\n","import { IS_SAFARI } from './environment';\nimport safePlay from './safePlay';\nimport { patchSafariProgressiveAudio, isSafariPatchInProgress } from './patchSafariProgressiveAudio';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { parseMessageKey } from '../modules/helpers';\n\ntype Handler = (eventName: string, e: Event) => void;\n\ninterface Track {\n audio: HTMLAudioElement;\n proxy: HTMLAudioElement;\n handlers: Handler[];\n onForcePlay?: NoneToVoidFunction;\n}\n\nconst tracks = new Map();\nlet queue: string[] = [];\n\nlet currentTrackId: string | undefined;\n\nfunction createAudio(trackId: string, onForcePlay?: NoneToVoidFunction) {\n const audio = new Audio();\n\n function handleEvent(eventName: string) {\n return (e: Event) => {\n if (!tracks.has(trackId)) {\n return;\n }\n\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n tracks.get(trackId)!.handlers.forEach((handler) => {\n handler(eventName, e);\n });\n };\n }\n\n audio.addEventListener('timeupdate', handleEvent('onTimeUpdate'));\n audio.addEventListener('play', handleEvent('onPlay'));\n audio.addEventListener('pause', handleEvent('onPause'));\n audio.addEventListener('loadstart', handleEvent('onLoadStart'));\n audio.addEventListener('loadeddata', handleEvent('onLoadedData'));\n audio.addEventListener('playing', handleEvent('onPlaying'));\n audio.addEventListener('ended', () => {\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n const nextTrackId = queue[queue.indexOf(trackId) + 1];\n if (!nextTrackId) {\n return;\n }\n\n if (!tracks.has(nextTrackId)) {\n // A bit hacky way to continue playlist when switching chat\n getDispatch().openAudioPlayer(parseMessageKey(nextTrackId));\n\n return;\n }\n\n const nextTrack = tracks.get(nextTrackId)!;\n\n if (nextTrack.onForcePlay) {\n nextTrack.onForcePlay();\n }\n\n currentTrackId = nextTrackId;\n\n if (nextTrack.audio.src) {\n safePlay(nextTrack.audio);\n }\n });\n\n return {\n audio,\n proxy: new Proxy(audio, {\n get: (origin, key: keyof HTMLAudioElement) => origin[key],\n }),\n handlers: [],\n onForcePlay,\n };\n}\n\nexport function stopCurrentAudio() {\n const currentTrack = currentTrackId && tracks.get(currentTrackId);\n if (currentTrack) {\n currentTrack.audio.pause();\n }\n}\n\nexport function register(trackId: string, handler: Handler, onForcePlay?: NoneToVoidFunction) {\n if (!tracks.has(trackId)) {\n tracks.set(trackId, createAudio(trackId, onForcePlay));\n\n if (!queue.includes(trackId)) {\n queue.push(trackId);\n }\n }\n\n const { audio, proxy, handlers } = tracks.get(trackId)!;\n\n handlers.push(handler);\n\n return {\n play(src: string) {\n if (currentTrackId && currentTrackId !== trackId) {\n tracks.get(currentTrackId)!.audio.pause();\n }\n\n currentTrackId = trackId;\n\n if (!audio.src) {\n audio.src = src;\n audio.preload = 'auto';\n\n if (src.includes('/progressive/') && IS_SAFARI) {\n patchSafariProgressiveAudio(audio);\n }\n }\n\n safePlay(audio);\n },\n\n pause() {\n if (currentTrackId === trackId) {\n audio.pause();\n }\n },\n\n setCurrentTime(time: number) {\n if (currentTrackId === trackId) {\n audio.currentTime = time;\n }\n },\n\n proxy,\n\n destroy(shouldRemoveFromQueue = false) {\n const track = tracks.get(trackId);\n if (!track) {\n return;\n }\n\n track.handlers = track.handlers.filter((h) => h !== handler);\n\n if (!track.handlers.length) {\n track.audio.pause();\n tracks.delete(trackId);\n\n if (shouldRemoveFromQueue) {\n queue = queue.filter((id) => id !== trackId);\n }\n\n if (trackId === currentTrackId) {\n currentTrackId = undefined;\n }\n }\n },\n };\n}\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n link.click();\n}\n","import { RefObject } from 'react';\nimport React, { FC, memo, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport buildClassName from '../../util/buildClassName';\nimport { formatMediaDateTime, formatPastTimeShort } from '../../util/dateFormat';\nimport { getColorFromExtension, getFileSizeString } from './helpers/documentInfo';\nimport { getDocumentThumbnailDimensions } from './helpers/mediaDimensions';\nimport renderText from './helpers/renderText';\n\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './File.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n name: string;\n extension?: string;\n size: number;\n timestamp?: number;\n sender?: string;\n thumbnailDataUri?: string;\n previewData?: string;\n className?: string;\n smaller?: boolean;\n isTransferring?: boolean;\n isUploading?: boolean;\n isSelectable?: boolean;\n isSelected?: boolean;\n transferProgress?: number;\n onClick?: () => void;\n onDateClick?: (e: React.MouseEvent) => void;\n};\n\nconst File: FC = ({\n ref,\n name,\n size,\n extension = '',\n timestamp,\n sender,\n thumbnailDataUri,\n previewData,\n className,\n smaller,\n isTransferring,\n isUploading,\n isSelectable,\n isSelected,\n transferProgress,\n onClick,\n onDateClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, true);\n const color = getColorFromExtension(extension);\n const sizeString = getFileSizeString(size);\n\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewData, 'slow');\n const { width, height } = getDocumentThumbnailDimensions(smaller);\n\n const fullClassName = buildClassName(\n 'File',\n className,\n smaller && 'smaller',\n onClick && !isUploading && 'interactive',\n isSelected && 'file-is-selected',\n );\n\n return (\n
\n {isSelectable && (\n
\n {isSelected && }\n
\n )}\n
\n {thumbnailDataUri || previewData ? (\n
\n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n
\n ) : (\n
\n {extension.length <= 4 && (\n {extension}\n )}\n
\n )}\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {onClick && }\n
\n
\n
{renderText(name)}
\n
\n \n {isTransferring && transferProgress ? `${Math.round(transferProgress * 100)}%` : sizeString}\n \n {sender && {renderText(sender)}}\n {!sender && timestamp && (\n <>\n {' '}\n {formatMediaDateTime(timestamp * 1000)}\n \n )}\n
\n
\n {sender && timestamp && (\n {formatPastTimeShort(timestamp * 1000)}\n )}\n
\n );\n};\n\nexport default memo(File);\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-cond-assign */\n/* eslint-disable no-param-reassign */\n/* eslint-disable prefer-const */\n/* eslint-disable eqeqeq */\n\n/*\nSuperfast Blur - a fast Box Blur For Canvas\n\nVersion: 0.5\nAuthor: Mario Klingemann\nContact: mario@quasimondo.com\nWebsite: http://www.quasimondo.com/BoxBlurForCanvas\nTwitter: @quasimondo\n\nIn case you find this class useful - especially in commercial projects -\nI am not totally unhappy for a small donation to my PayPal account\nmario@quasimondo.de\n\nOr support me on flattr:\nhttps://flattr.com/thing/140066/Superfast-Blur-a-pretty-fast-Box-Blur-Effect-for-CanvasJavascript\n\nCopyright (c) 2011 Mario Klingemann\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// eslint-disable-next-line max-len\nconst mul_table = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];\n// eslint-disable-next-line max-len\nconst shg_table = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];\n\nexport default function boxBlurCanvasRGB(context, top_x, top_y, width, height, radius, iterations) {\n if (Number.isNaN(radius) || radius < 1) return;\n\n radius |= 0;\n\n if (Number.isNaN(iterations)) iterations = 1;\n iterations |= 0;\n if (iterations > 3) iterations = 3;\n if (iterations < 1) iterations = 1;\n\n const imageData = context.getImageData(top_x, top_y, width, height);\n\n const pixels = imageData.data;\n\n let rsum;\n let gsum;\n let bsum;\n let x;\n let y;\n let i;\n let p;\n let p1;\n let p2;\n let yp;\n let yi;\n let yw;\n let wm = width - 1;\n let hm = height - 1;\n let rad1 = radius + 1;\n\n let r = [];\n let g = [];\n let b = [];\n\n let mul_sum = mul_table[radius];\n let shg_sum = shg_table[radius];\n\n let vmin = [];\n let vmax = [];\n\n while (iterations-- > 0) {\n yw = yi = 0;\n\n for (y = 0; y < height; y++) {\n rsum = pixels[yw] * rad1;\n gsum = pixels[yw + 1] * rad1;\n bsum = pixels[yw + 2] * rad1;\n\n for (i = 1; i <= radius; i++) {\n p = yw + (((i > wm ? wm : i)) << 2);\n rsum += pixels[p++];\n gsum += pixels[p++];\n bsum += pixels[p++];\n }\n\n for (x = 0; x < width; x++) {\n r[yi] = rsum;\n g[yi] = gsum;\n b[yi] = bsum;\n\n if (y == 0) {\n vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;\n vmax[x] = ((p = x - radius) > 0 ? p << 2 : 0);\n }\n\n p1 = yw + vmin[x];\n p2 = yw + vmax[x];\n\n rsum += pixels[p1++] - pixels[p2++];\n gsum += pixels[p1++] - pixels[p2++];\n bsum += pixels[p1++] - pixels[p2++];\n\n yi++;\n }\n yw += (width << 2);\n }\n\n for (x = 0; x < width; x++) {\n yp = x;\n rsum = r[yp] * rad1;\n gsum = g[yp] * rad1;\n bsum = b[yp] * rad1;\n\n for (i = 1; i <= radius; i++) {\n yp += (i > hm ? 0 : width);\n rsum += r[yp];\n gsum += g[yp];\n bsum += b[yp];\n }\n\n yi = x << 2;\n for (y = 0; y < height; y++) {\n pixels[yi] = (rsum * mul_sum) >>> shg_sum;\n pixels[yi + 1] = (gsum * mul_sum) >>> shg_sum;\n pixels[yi + 2] = (bsum * mul_sum) >>> shg_sum;\n\n if (x == 0) {\n vmin[y] = ((p = y + rad1) < hm ? p : hm) * width;\n vmax[y] = ((p = y - radius) > 0 ? p * width : 0);\n }\n\n p1 = x + vmin[y];\n p2 = x + vmax[y];\n\n rsum += r[p1] - r[p2];\n gsum += g[p1] - g[p2];\n bsum += b[p1] - b[p2];\n\n yi += width << 2;\n }\n }\n }\n\n context.putImageData(imageData, top_x, top_y);\n}\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../lib/teact/teact';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport buildClassName from '../../util/buildClassName';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\n\nimport Portal from './Portal';\n\nimport './Notification.scss';\n\ntype OwnProps = {\n message: TextPart[];\n duration?: number;\n onDismiss: () => void;\n};\n\nconst DEFAULT_DURATION = 3000;\nconst ANIMATION_DURATION = 150;\n\nconst Notification: FC = ({ message, duration = DEFAULT_DURATION, onDismiss }) => {\n const [isOpen, setIsOpen] = useState(true);\n // eslint-disable-next-line no-null/no-null\n const timerRef = useRef(null);\n\n const { transitionClassNames } = useShowTransition(isOpen);\n\n const closeAndDismiss = useCallback(() => {\n setIsOpen(false);\n setTimeout(onDismiss, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [onDismiss]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(closeAndDismiss) : undefined), [isOpen, closeAndDismiss]);\n\n useEffect(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n\n return () => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n };\n }, [duration, closeAndDismiss]);\n\n const handleMouseEnter = useCallback(() => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n }, [duration, closeAndDismiss]);\n\n return (\n \n \n
\n {message}\n
\n
\n \n );\n};\n\nexport default memo(Notification);\n","import { EDITABLE_INPUT_ID } from '../../../../config';\n\nconst MAX_NESTING_PARENTS = 5;\n\nexport function isSelectionInsideInput(selectionRange: Range) {\n const { commonAncestorContainer } = selectionRange;\n let parentNode: HTMLElement | null = commonAncestorContainer as HTMLElement;\n let iterations = 1;\n while (parentNode && parentNode.id !== EDITABLE_INPUT_ID && iterations < MAX_NESTING_PARENTS) {\n parentNode = parentNode.parentElement;\n iterations++;\n }\n\n return Boolean(parentNode && parentNode.id === EDITABLE_INPUT_ID);\n}\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useEffect, useRef, memo, useState, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { IAnchorPosition, ISettings } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { selectCurrentMessageList, selectReplyingToId } from '../../../modules/selectors';\nimport { debounce } from '../../../util/schedulers';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport {\n IS_ANDROID, IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport useLayoutEffectWithPrevDeps from '../../../hooks/useLayoutEffectWithPrevDeps';\nimport useFlag from '../../../hooks/useFlag';\nimport parseEmojiOnlyString from '../../common/helpers/parseEmojiOnlyString';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport TextFormatter from './TextFormatter';\n\nconst CONTEXT_MENU_CLOSE_DELAY_MS = 100;\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 350;\nconst TRANSITION_DURATION_FACTOR = 50;\n\ntype OwnProps = {\n id: string;\n editableInputId?: string;\n html: string;\n placeholder: string;\n shouldSetFocus: boolean;\n shouldSupressFocus?: boolean;\n onUpdate: (html: string) => void;\n onSupressedFocus?: () => void;\n onSend: () => void;\n};\n\ntype StateProps = {\n currentChatId?: number;\n replyingToId?: number;\n noTabCapture?: boolean;\n messageSendKeyCombo?: ISettings['messageSendKeyCombo'];\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_INPUT_HEIGHT = IS_MOBILE_SCREEN ? 256 : 416;\nconst TAB_INDEX_PRIORITY_TIMEOUT = 2000;\nconst TEXT_FORMATTER_SAFE_AREA_PX = 90;\n// For some reason Safari inserts `
` after user removes text from input\nconst SAFARI_BR = '
';\n\nfunction clearSelection() {\n const selection = window.getSelection();\n if (!selection) {\n return;\n }\n\n if (selection.removeAllRanges) {\n selection.removeAllRanges();\n } else if (selection.empty) {\n selection.empty();\n }\n}\n\nconst MessageInput: FC = ({\n id,\n editableInputId,\n html,\n placeholder,\n shouldSetFocus,\n shouldSupressFocus,\n onUpdate,\n onSupressedFocus,\n onSend,\n currentChatId,\n replyingToId,\n noTabCapture,\n messageSendKeyCombo,\n editLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const cloneRef = useRef(null);\n\n const isContextMenuOpenRef = useRef(false);\n const [isTextFormatterOpen, openTextFormatter, closeTextFormatter] = useFlag();\n const [textFormatterAnchorPosition, setTextFormatterAnchorPosition] = useState();\n const [selectedRange, setSelectedRange] = useState();\n\n useLayoutEffectWithPrevDeps(([prevHtml]) => {\n if (html !== inputRef.current!.innerHTML) {\n inputRef.current!.innerHTML = html;\n }\n\n if (html !== cloneRef.current!.innerHTML) {\n cloneRef.current!.innerHTML = html;\n }\n\n if (prevHtml !== undefined && prevHtml !== html) {\n updateInputHeight(!html.length);\n }\n }, [html]);\n\n const focusInput = useCallback(() => {\n // Avoid focusing during animation\n if (inputRef.current!.closest('.from, .to')) {\n setTimeout(focusInput, FOCUS_DELAY_MS);\n return;\n }\n\n focusEditableElement(inputRef.current!);\n }, []);\n\n const handleCloseTextFormatter = useCallback(() => {\n closeTextFormatter();\n clearSelection();\n }, [closeTextFormatter]);\n\n function checkSelection() {\n // Disable the formatter on iOS devices for now.\n if (IS_IOS) {\n return;\n }\n\n const selection = window.getSelection();\n if (!selection || !selection.rangeCount || isContextMenuOpenRef.current) {\n closeTextFormatter();\n return;\n }\n\n const selectionRange = selection.getRangeAt(0);\n const selectedText = selectionRange.toString().trim();\n if (\n !isSelectionInsideInput(selectionRange)\n || !selectedText\n || parseEmojiOnlyString(selectedText)\n || !selectionRange.START_TO_END\n ) {\n closeTextFormatter();\n return;\n }\n\n const selectionRect = selectionRange.getBoundingClientRect();\n const inputRect = inputRef.current!.getBoundingClientRect();\n\n let x = (selectionRect.left + selectionRect.width / 2) - inputRect.left;\n\n if (x < TEXT_FORMATTER_SAFE_AREA_PX) {\n x = TEXT_FORMATTER_SAFE_AREA_PX;\n } else if (x > inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX) {\n x = inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX;\n }\n\n setTextFormatterAnchorPosition({\n x,\n y: selectionRect.top - inputRect.top,\n });\n\n setSelectedRange(selectionRange);\n openTextFormatter();\n }\n\n function handleMouseDown(event: React.MouseEvent) {\n function handleMouseUp() {\n checkSelection();\n\n event.target.removeEventListener('mouseup', handleMouseUp);\n }\n\n if (event.button !== 2) {\n event.target.addEventListener('mouseup', handleMouseUp);\n return;\n }\n\n if (isContextMenuOpenRef.current === true) {\n return;\n }\n\n isContextMenuOpenRef.current = true;\n\n function closeContextMenuMouseListener() {\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('mouseup', closeContextMenuMouseListener);\n }\n\n function closeContextMenuKeyListener(e: KeyboardEvent) {\n if (e.key !== 'Esc' && e.key !== 'Escape') {\n return;\n }\n\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('keydown', closeContextMenuKeyListener);\n }\n\n document.addEventListener('mousedown', closeContextMenuMouseListener);\n document.addEventListener('keydown', closeContextMenuKeyListener);\n }\n\n function handleKeyDown(e: React.KeyboardEvent) {\n function handleKeyUp() {\n checkSelection();\n\n e.target.removeEventListener('keyup', handleKeyUp);\n }\n\n if (e.key === 'Enter' && !e.shiftKey) {\n if (\n !(IS_IOS || IS_ANDROID)\n && (\n (messageSendKeyCombo === 'enter' && !e.shiftKey)\n || (messageSendKeyCombo === 'ctrl-enter' && (e.ctrlKey || e.metaKey))\n )\n ) {\n e.preventDefault();\n\n closeTextFormatter();\n onSend();\n }\n } else if (e.key === 'ArrowUp' && !html.length) {\n e.preventDefault();\n editLastMessage();\n } else {\n e.target.addEventListener('keyup', handleKeyUp);\n }\n }\n\n function handleTouchSelection() {\n if (!IS_ANDROID) {\n return;\n }\n\n checkSelection();\n }\n\n function handleChange(e: ChangeEvent) {\n const { innerHTML, textContent } = e.currentTarget;\n\n onUpdate(innerHTML === SAFARI_BR ? '' : innerHTML);\n\n // Reset focus on the input to remove any active styling when input is cleared\n if (!IS_TOUCH_ENV && (!textContent || !textContent.length)) {\n const selection = window.getSelection()!;\n if (selection) {\n inputRef.current!.blur();\n selection.removeAllRanges();\n focusEditableElement(inputRef.current!, true);\n }\n }\n }\n\n function stopEvent(e: React.MouseEvent) {\n if (!IS_ANDROID) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n }\n\n function updateInputHeight(willSend = false) {\n const input = inputRef.current!;\n const clone = cloneRef.current!;\n const currentHeight = Number(input.style.height.replace('px', ''));\n const newHeight = Math.min(clone.scrollHeight, MAX_INPUT_HEIGHT);\n if (newHeight === currentHeight) {\n return;\n }\n\n const transitionDuration = Math.round(\n TRANSITION_DURATION_FACTOR * Math.log(Math.abs(newHeight - currentHeight)),\n );\n\n const exec = () => {\n input.style.height = `${newHeight}px`;\n input.style.transitionDuration = `${transitionDuration}ms`;\n input.classList.toggle('overflown', clone.scrollHeight > MAX_INPUT_HEIGHT);\n };\n\n if (willSend) {\n // Sync with sending animation\n requestAnimationFrame(exec);\n } else {\n exec();\n }\n }\n\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n focusInput();\n }, [currentChatId, focusInput, replyingToId, shouldSetFocus]);\n\n useEffect(() => {\n if (noTabCapture) {\n return undefined;\n }\n\n const captureFirstTab = debounce((e: KeyboardEvent) => {\n if (e.key === 'Tab') {\n e.preventDefault();\n requestAnimationFrame(focusInput);\n }\n }, TAB_INDEX_PRIORITY_TIMEOUT, true, false);\n\n return captureKeyboardListeners({ onTab: captureFirstTab });\n }, [focusInput, noTabCapture]);\n\n useEffect(() => {\n const input = inputRef.current!;\n\n function supressFocus() {\n input.blur();\n }\n\n if (shouldSupressFocus) {\n input.addEventListener('focus', supressFocus);\n }\n\n return () => {\n input.removeEventListener('focus', supressFocus);\n };\n }, [shouldSupressFocus]);\n\n const className = buildClassName(\n 'form-control custom-scroll',\n html.length > 0 && 'touched',\n shouldSupressFocus && 'focus-disabled',\n );\n\n return (\n
\n \n
\n {placeholder}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: currentChatId, threadId } = selectCurrentMessageList(global) || {};\n const { messageSendKeyCombo } = global.settings.byKey;\n\n return {\n currentChatId,\n messageSendKeyCombo,\n replyingToId: currentChatId && threadId ? selectReplyingToId(global, currentChatId, threadId) : undefined,\n noTabCapture: global.isPollModalOpen || global.payment.isPaymentModalOpen,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editLastMessage']),\n)(MessageInput));\n","import { useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport useOnChange from './useOnChange';\nimport useBlur from './useBlur';\nimport { imgToCanvas } from '../util/files';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\n\nexport default function useBlurSync(dataUri: string | false | undefined) {\n const blurredRef = useRef();\n\n let isChanged = false;\n\n useOnChange(() => {\n isChanged = true;\n\n blurredRef.current = undefined;\n\n if (!dataUri) {\n return;\n }\n\n const img = new Image();\n img.src = dataUri;\n if (!img.width) {\n return;\n }\n\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n\n blurredRef.current = canvas.toDataURL();\n }, [dataUri]);\n\n // Sometimes `Image` do not manage to load synchronously,\n // so we fall back the non-blurred variant and prepare the async one at least for the next time\n const blurredAsync = useBlur(dataUri || undefined, Boolean(blurredRef.current));\n\n return blurredRef.current || (!isChanged && blurredAsync) || dataUri || undefined;\n}\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiWebPage } from '../../api/types';\n\nimport { getFirstLinkInMessage, getMessageSummaryText, getMessageWebPage } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport trimText from '../../util/trimText';\nimport renderText from './helpers/renderText';\nimport { formatPastTimeShort } from '../../util/dateFormat';\n\nimport Media from './Media';\nimport Link from '../ui/Link';\nimport SafeLink from './SafeLink';\n\nimport './WebLink.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n onMessageClick: (messageId: number, chatId: number) => void;\n};\n\nconst WebLink: FC = ({ message, senderTitle, onMessageClick }) => {\n let linkData: ApiWebPage | undefined = getMessageWebPage(message);\n\n if (!linkData) {\n const link = getFirstLinkInMessage(message);\n if (link) {\n const { url, domain } = link;\n const messageText = getMessageSummaryText(message);\n\n linkData = {\n siteName: domain.replace(/^www./, ''),\n url: url.includes('://') ? url : url.includes('@') ? `mailto:${url}` : `http://${url}`,\n description: messageText !== url ? messageText : undefined,\n } as ApiWebPage;\n }\n }\n\n const handleMessageClick = useCallback(() => {\n onMessageClick(message.id, message.chatId);\n }, [onMessageClick, message.id, message.chatId]);\n\n if (!linkData) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = linkData;\n\n const truncatedDescription = !senderTitle && trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebLink scroll-item',\n !photo && 'without-photo',\n );\n\n return (\n \n {photo && (\n \n )}\n
\n {renderText(title || siteName || displayUrl)}\n {truncatedDescription && (\n {renderText(truncatedDescription)}\n )}\n \n {url.replace('mailto:', '') || displayUrl}\n \n {senderTitle &&
{renderText(senderTitle)}
}\n
\n {senderTitle && (\n
\n \n {formatPastTimeShort(message.date * 1000)}\n \n
\n )}\n
\n );\n};\n\nexport default memo(WebLink);\n","import { useCallback } from '../../../../lib/teact/teact';\n\nexport enum ChatAnimationTypes {\n Move,\n Opacity,\n None,\n}\n\nexport function useChatAnimationType(orderDiffById: Record) {\n const movesUp = useCallback((id: number) => orderDiffById[id] < 0, [orderDiffById]);\n const movesDown = useCallback((id: number) => orderDiffById[id] > 0, [orderDiffById]);\n\n const orderDiffIds = Object.keys(orderDiffById).map(Number);\n const numberOfUp = orderDiffIds.filter(movesUp).length;\n const numberOfDown = orderDiffIds.filter(movesDown).length;\n\n return useCallback((chatId: number): ChatAnimationTypes => {\n const orderDiff = orderDiffById[chatId];\n\n if (orderDiff === 0) {\n return ChatAnimationTypes.None;\n }\n\n if (\n orderDiff === Infinity\n || orderDiff === -Infinity\n || (movesUp(chatId) && numberOfUp <= numberOfDown)\n || (movesDown(chatId) && numberOfDown < numberOfUp)\n ) {\n return ChatAnimationTypes.Opacity;\n }\n\n return ChatAnimationTypes.Move;\n }, [movesDown, movesUp, numberOfDown, numberOfUp, orderDiffById]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\n\nimport ShowTransition from '../../ui/ShowTransition';\n\nimport './Badge.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n isPinned?: boolean;\n};\n\nconst Badge: FC = ({ chat, isPinned }) => {\n const isShown = Boolean(chat.unreadCount || chat.hasUnreadMark || isPinned);\n const className = buildClassName(\n 'Badge',\n chat.isMuted && 'muted',\n isPinned && 'pinned',\n Boolean(chat.unreadCount || chat.hasUnreadMark) && 'unread',\n );\n\n function renderContent() {\n if (chat.unreadCount) {\n if (chat.unreadMentionsCount) {\n return (\n
\n
\n \n
\n
\n {formatIntegerCompact(chat.unreadCount)}\n
\n
\n );\n }\n\n return (\n
\n {formatIntegerCompact(chat.unreadCount)}\n
\n );\n } else if (chat.hasUnreadMark) {\n return (\n
\n );\n } else if (isPinned) {\n return (\n
\n \n
\n );\n }\n\n return undefined;\n }\n\n return (\n \n {renderContent}\n \n );\n};\n\nexport default Badge;\n","import React, {\n FC, memo, useCallback, useLayoutEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport useLang from '../../../hooks/useLang';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus, ApiFormattedText, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n isChatPrivate,\n isActionMessage,\n getPrivateChatUserId,\n getMessageAction,\n getMessageSenderName,\n isChatChannel,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageSticker,\n} from '../../../modules/helpers';\nimport {\n selectChat, selectUser, selectChatMessage, selectOutgoingStatus, selectDraft, selectCurrentMessageList,\n} from '../../../modules/selectors';\nimport { renderActionMessageText } from '../../common/helpers/renderActionMessageText';\nimport renderText from '../../common/helpers/renderText';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport useMedia from '../../../hooks/useMedia';\nimport { ChatAnimationTypes } from './hooks';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport TypingStatus from '../../common/TypingStatus';\nimport LastMessageMeta from '../../common/LastMessageMeta';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\nimport Badge from './Badge';\n\nimport './Chat.scss';\n\ntype OwnProps = {\n style?: string;\n chatId: number;\n folderId?: number;\n orderDiff: number;\n animationType: ChatAnimationTypes;\n isSelected: boolean;\n isPinned?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n actionTargetUser?: ApiUser;\n actionTargetMessage?: ApiMessage;\n actionTargetChatId?: number;\n lastMessageSender?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n draft?: ApiFormattedText;\n messageListType?: MessageListType;\n animationLevel?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 200;\n\nconst Chat: FC = ({\n style,\n chatId,\n folderId,\n orderDiff,\n animationType,\n isSelected,\n isPinned,\n chat,\n privateChatUser,\n actionTargetUser,\n lastMessageSender,\n lastMessageOutgoingStatus,\n actionTargetMessage,\n actionTargetChatId,\n draft,\n messageListType,\n animationLevel,\n lastSyncTime,\n openChat,\n focusLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const { lastMessage, typingStatus } = chat || {};\n const isAction = lastMessage && isActionMessage(lastMessage);\n\n useEnsureMessage(chatId, isAction ? lastMessage!.replyToMessageId : undefined, actionTargetMessage);\n\n const mediaThumbnail = lastMessage && !getMessageSticker(lastMessage)\n ? getMessageMediaThumbDataUri(lastMessage)\n : undefined;\n const mediaBlobUrl = useMedia(lastMessage ? getMessageMediaHash(lastMessage, 'micro') : undefined);\n\n // Sets animation excess values when `orderDiff` changes and then resets excess values to animate.\n useLayoutEffect(() => {\n if (animationLevel === 0) {\n return;\n }\n\n const element = ref.current!;\n\n // TODO Refactor animation: create `useListAnimation` that owns `orderDiff` and `animationType`\n if (animationType === ChatAnimationTypes.Opacity) {\n element.style.opacity = '0';\n\n fastRaf(() => {\n element.classList.add('animate-opacity');\n element.style.opacity = '1';\n });\n } else if (animationType === ChatAnimationTypes.Move) {\n element.style.transform = `translate3d(0, ${-orderDiff * 100}%, 0)`;\n\n fastRaf(() => {\n element.classList.add('animate-transform');\n element.style.transform = '';\n });\n } else {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n element.classList.remove('animate-opacity', 'animate-transform');\n element.style.opacity = '';\n element.style.transform = '';\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [animationLevel, orderDiff, animationType]);\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId });\n\n if (isSelected && messageListType === 'thread') {\n focusLastMessage();\n }\n }, [\n isSelected,\n messageListType,\n openChat,\n chatId,\n focusLastMessage,\n ]);\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n handleDelete: openDeleteModal,\n folderId,\n isPinned,\n });\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderLastMessageOrTyping() {\n if (typingStatus && lastMessage && typingStatus.timestamp > lastMessage.date * 1000) {\n return ;\n }\n\n if (draft && draft.text.length) {\n return (\n

\n {lang('Draft')}\n {renderText(draft.text)}\n

\n );\n }\n\n if (!lastMessage) {\n return undefined;\n }\n\n if (isAction) {\n const actionOrigin = chat && (isChatChannel(chat) || lastMessage.senderId === lastMessage.chatId)\n ? chat\n : lastMessageSender;\n\n return (\n

\n {renderText(renderActionMessageText(\n lastMessage,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string)}\n

\n );\n }\n\n const senderName = getMessageSenderName(chatId, lastMessageSender);\n\n return (\n

\n {senderName && (\n {renderText(senderName)}\n )}\n {renderMessageSummary(lastMessage!, mediaBlobUrl || mediaThumbnail)}\n

\n );\n }\n\n const className = buildClassName(\n 'Chat chat-item-clickable',\n isChatPrivate(chatId) ? 'private' : 'group',\n isSelected && !IS_MOBILE_SCREEN && 'selected',\n );\n\n return (\n \n \n
\n
\n

{renderText(getChatTitle(chat, privateChatUser))}

\n {chat.isVerified && }\n {chat.isMuted && }\n {chat.lastMessage && (\n \n )}\n
\n
\n {renderLastMessageOrTyping()}\n \n
\n
\n \n \n );\n};\n\nfunction renderMessageSummary(message: ApiMessage, blobUrl?: string) {\n if (!blobUrl) {\n return renderText(getMessageSummaryText(message));\n }\n\n return (\n \n \"\"\n {getMessageVideo(message) && }\n {renderText(getMessageSummaryText(message, true))}\n \n );\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return {};\n }\n\n const { senderId, replyToMessageId, isOutgoing } = chat.lastMessage;\n const lastMessageSender = senderId ? selectUser(global, senderId) : undefined;\n const lastMessageAction = getMessageAction(chat.lastMessage);\n const actionTargetMessage = lastMessageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const { targetUserId: actionTargetUserId, targetChatId: actionTargetChatId } = lastMessageAction || {};\n const privateChatUserId = getPrivateChatUserId(chat);\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n\n return {\n chat,\n lastMessageSender,\n ...(isOutgoing && { lastMessageOutgoingStatus: selectOutgoingStatus(global, chat.lastMessage) }),\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n ...(actionTargetUserId && { actionTargetUser: selectUser(global, actionTargetUserId) }),\n actionTargetChatId,\n actionTargetMessage,\n draft: selectDraft(global, chatId, MAIN_THREAD_ID),\n messageListType,\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'focusLastMessage',\n ]),\n)(Chat));\n","import React, {\n FC, memo, useMemo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiChatFolder, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { ALL_CHATS_PRELOAD_DISABLED, CHAT_HEIGHT_PX, CHAT_LIST_SLICE } from '../../../config';\nimport { IS_ANDROID } from '../../../util/environment';\nimport usePrevious from '../../../hooks/usePrevious';\nimport { mapValues, pick } from '../../../util/iteratees';\nimport { getChatOrder, prepareChatList, prepareFolderListIds } from '../../../modules/helpers';\nimport { selectChatFolder, selectCurrentMessageList } from '../../../modules/selectors';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\nimport { useChatAnimationType } from './hooks';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Loading from '../../ui/Loading';\nimport Chat from './Chat';\n\ntype OwnProps = {\n folderType: 'all' | 'archived' | 'folder';\n folderId?: number;\n noChatsText?: string;\n};\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFolder?: ApiChatFolder;\n listIds?: number[];\n currentChatId?: number;\n orderedPinnedIds?: number[];\n lastSyncTime?: number;\n isInDiscussionThread?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nenum FolderTypeToListType {\n 'all' = 'active',\n 'archived' = 'archived'\n}\n\nconst ChatList: FC = ({\n folderType,\n folderId,\n noChatsText = 'Chat list is empty.',\n chatFolder,\n chatsById,\n usersById,\n listIds,\n currentChatId,\n orderedPinnedIds,\n lastSyncTime,\n isInDiscussionThread,\n loadMoreChats,\n preloadTopChatMessages,\n}) => {\n const [currentListIds, currentPinnedIds] = useMemo(() => {\n return folderType === 'folder' && chatFolder\n ? prepareFolderListIds(chatsById, usersById, chatFolder)\n : [listIds, orderedPinnedIds];\n }, [folderType, chatsById, usersById, chatFolder, listIds, orderedPinnedIds]);\n\n const [orderById, orderedIds] = useMemo(() => {\n if (!currentListIds || (folderType === 'folder' && !chatFolder)) {\n return [];\n }\n const newChatArrays = prepareChatList(chatsById, currentListIds, currentPinnedIds, folderType);\n const singleList = [...newChatArrays.pinnedChats, ...newChatArrays.otherChats];\n const newOrderedIds = singleList.map(({ id }) => id);\n const newOrderById = singleList.reduce((acc, chat, i) => {\n acc[chat.id] = i;\n return acc;\n }, {} as Record);\n\n return [newOrderById, newOrderedIds];\n }, [currentListIds, currentPinnedIds, folderType, chatFolder, chatsById]);\n\n const prevOrderById = usePrevious(orderById);\n\n const orderDiffById = orderById && prevOrderById\n ? mapValues(orderById, (order, id) => {\n return order - (prevOrderById[id] !== undefined ? prevOrderById[id] : Infinity);\n })\n : {};\n\n const loadMoreOfType = useCallback(() => {\n loadMoreChats({ listType: folderType === 'archived' ? 'archived' : 'active' });\n }, [loadMoreChats, folderType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? loadMoreOfType : undefined,\n orderedIds,\n undefined,\n CHAT_LIST_SLICE,\n folderType === 'all' && !ALL_CHATS_PRELOAD_DISABLED,\n );\n\n // TODO Refactor to not call `prepareChatList` twice\n const chatArrays = viewportIds && prepareChatList(chatsById, viewportIds, currentPinnedIds, folderType);\n\n useEffect(() => {\n if (lastSyncTime && folderType === 'all') {\n preloadTopChatMessages();\n }\n }, [lastSyncTime, folderType, preloadTopChatMessages]);\n\n const getAnimationType = useChatAnimationType(orderDiffById);\n\n function renderChats() {\n const viewportOffset = orderedIds!.indexOf(viewportIds![0]);\n const pinnedOffset = viewportOffset + chatArrays!.pinnedChats.length;\n\n return (\n \n {chatArrays!.pinnedChats.map(({ id }, i) => (\n \n ))}\n {chatArrays!.otherChats.map((chat, i) => (\n \n ))}\n
\n );\n }\n\n return (\n \n {viewportIds && viewportIds.length && chatArrays ? (\n renderChats()\n ) : viewportIds && !viewportIds.length ? (\n
{noChatsText}
\n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { folderType, folderId }): StateProps => {\n const {\n chats: {\n listIds,\n byId: chatsById,\n orderedPinnedIds,\n },\n users: { byId: usersById },\n lastSyncTime,\n } = global;\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n const listType = folderType !== 'folder' ? FolderTypeToListType[folderType] : undefined;\n const chatFolder = folderId ? selectChatFolder(global, folderId) : undefined;\n\n return {\n chatsById,\n usersById,\n currentChatId,\n lastSyncTime,\n ...(listType ? {\n listIds: listIds[listType],\n orderedPinnedIds: orderedPinnedIds[listType],\n } : {\n chatFolder,\n }),\n isInDiscussionThread: currentThreadId !== MAIN_THREAD_ID,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMoreChats', 'preloadTopChatMessages']),\n)(ChatList));\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","import { useCallback, useEffect, useState } from '../../../../lib/teact/teact';\n\nimport { ApiMessageEntityTypes, ApiChatMember, ApiUser } from '../../../../api/types';\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport { getUserFirstOrLastName } from '../../../../modules/helpers';\nimport searchUserName from '../helpers/searchUserName';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst RE_NOT_USERNAME_SEARCH = /[^@_\\d\\wа-яё]+/i;\n\nexport default function useMentionMenu(\n canSuggestMembers: boolean | undefined,\n html: string,\n onUpdateHtml: (html: string) => void,\n inputId: string = EDITABLE_INPUT_ID,\n groupChatMembers?: ApiChatMember[],\n currentUserId?: number,\n usersById?: Record,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [currentFilter, setCurrentFilter] = useState('');\n const [filteredMembers, setFilteredMembers] = useState([]);\n\n const getFilteredMembers = useCallback((filter) => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return groupChatMembers.filter(({ userId }) => {\n const user = usersById[userId];\n if (userId === currentUserId || !user) {\n return false;\n }\n\n return !filter || searchUserName(filter, user);\n });\n }, [groupChatMembers, currentUserId, usersById]);\n\n useEffect(() => {\n if (!canSuggestMembers || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const usernameFilter = getUsernameFilter(html);\n\n if (usernameFilter) {\n const filter = usernameFilter ? usernameFilter.substr(1) : '';\n const membersToMention = getFilteredMembers(filter);\n if (membersToMention && membersToMention.length) {\n markIsOpen();\n setCurrentFilter(filter);\n setFilteredMembers(membersToMention);\n } else {\n unmarkIsOpen();\n }\n } else {\n unmarkIsOpen();\n }\n }, [canSuggestMembers, html, getFilteredMembers, markIsOpen, unmarkIsOpen]);\n\n const insertMention = useCallback((user: ApiUser, forceFocus = false) => {\n if (!user.username && !getUserFirstOrLastName(user)) {\n return;\n }\n\n const insertedHtml = user.username\n ? `@${user.username}`\n : `${getUserFirstOrLastName(user)}`;\n\n const atIndex = html.lastIndexOf('@');\n if (atIndex !== -1) {\n onUpdateHtml(`${html.substr(0, atIndex)}${insertedHtml} `);\n const messageInput = document.getElementById(inputId)!;\n if (!IS_MOBILE_SCREEN) {\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, forceFocus);\n });\n }\n }\n\n unmarkIsOpen();\n }, [html, inputId, onUpdateHtml, unmarkIsOpen]);\n\n return {\n isMentionMenuOpen: isOpen,\n mentionFilter: currentFilter,\n closeMentionMenu: unmarkIsOpen,\n insertMention,\n mentionFilteredMembers: filteredMembers,\n };\n}\n\nfunction getUsernameFilter(html: string) {\n const tempEl = document.createElement('div');\n tempEl.innerHTML = html;\n const text = tempEl.innerText;\n\n const lastSymbol = text[text.length - 1];\n const lastWord = text.split(RE_NOT_USERNAME_SEARCH).pop();\n\n if (\n !text.length || RE_NOT_USERNAME_SEARCH.test(lastSymbol)\n || !lastWord || !lastWord.startsWith('@')\n ) {\n return undefined;\n }\n\n return lastWord;\n}\n","import { ApiUser } from '../../../../api/types';\nimport { getUserFullName } from '../../../../modules/helpers';\nimport searchWords from '../../../../util/searchWords';\n\n// TODO: Support cyrillic translit search\nexport default function searchUserName(filter: string, user: ApiUser) {\n const usernameLowered = user.username.toLowerCase();\n const fullName = getUserFullName(user);\n const fullNameLowered = fullName && fullName.toLowerCase();\n const filterLowered = filter.toLowerCase();\n\n return usernameLowered.startsWith(filterLowered) || (\n fullNameLowered && searchWords(fullNameLowered, filterLowered)\n );\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/0.6531d7c910f326b2774d.css b/dist/0.9a2173a5ef629d3739fc.css similarity index 100% rename from dist/0.6531d7c910f326b2774d.css rename to dist/0.9a2173a5ef629d3739fc.css diff --git a/dist/0.6531d7c910f326b2774d.js b/dist/0.9a2173a5ef629d3739fc.js similarity index 88% rename from dist/0.6531d7c910f326b2774d.js rename to dist/0.9a2173a5ef629d3739fc.js index 47de0f96..c72b90dd 100644 --- a/dist/0.6531d7c910f326b2774d.js +++ b/dist/0.9a2173a5ef629d3739fc.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[0],Array(94).concat([function(e,t,n){"use strict";var a=n(11),r=n(31),c=n(103);t.a=()=>{const e=Object(r.a)();return Object(c.a)(()=>a.a(e),[e]),a.b}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(8),s=n(132),i=n(163),o=n(35),l=n(47),u=n(34);n(197);t.a=e=>{const{ref:t,icon:n,className:d,style:m,children:h,disabled:b,ripple:f,narrow:p,inactive:g,focus:O,destructive:v,multiline:j,contextActions:E,onClick:y}=e;let N=Object(a.q)(null);t&&(N=t);const{isContextMenuOpen:T,contextMenuPosition:C,handleBeforeContextMenu:M,handleContextMenu:w,handleContextMenuClose:I,handleContextMenuHide:S}=Object(s.a)(N,!E),L=Object(a.m)(()=>N.current,[]),k=Object(a.m)(()=>N.current.closest(".custom-scroll"),[]),A=Object(a.m)(()=>N.current.querySelector(".ListItem-context-menu .bubble"),[]),{positionX:x,positionY:D,style:_}=Object(i.a)(C,L,k,A),R=Object(a.m)(e=>{!b&&y&&y(e)},[b,y]),P=Object(a.m)(e=>{g||r.k||(!E||2!==e.button&&y||M(e),0===e.button&&(y?R(e):w(e)))},[g,E,y,M,w,R]),F=Object(c.a)("ListItem no-selection",d,f&&"has-ripple",p&&"narrow",b&&"disabled",g&&"inactive",C&&"has-menu-open",O&&"focus",v&&"destructive",j&&"multiline");return a.a.createElement("div",{ref:N,className:F,style:m},a.a.createElement("div",{className:"ListItem-button",role:"button",tabIndex:0,onClick:!g&&r.k?R:void 0,onMouseDown:P,onContextMenu:!g&&E?w:void 0},n&&a.a.createElement("i",{className:"icon-"+n}),j&&a.a.createElement("div",{className:"multiline-item"},h),!j&&h,!b&&!g&&f&&a.a.createElement(o.a,null)),E&&void 0!==C&&a.a.createElement(l.a,{isOpen:T,positionX:x,positionY:D,style:_,className:"ListItem-context-menu",autoClose:!0,onClose:I,onCloseAnimationEnd:S},E.map(e=>a.a.createElement(u.a,{key:e.title,icon:e.icon,destructive:e.destructive,disabled:!e.handler,onClick:e.handler},e.title))))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return o}));var a=n(0),r=n(9),c=n(43);function s({rootRef:e,throttleMs:t,debounceMs:n,shouldSkipFirst:s,margin:i,threshold:o,isDisabled:l},u){const d=Object(a.q)(),m=Object(a.q)(),h=Object(a.q)(),b=Object(a.q)();m.current=u;const f=Object(a.m)(()=>{h.current=!0},[]),p=Object(a.m)(()=>{h.current=!1,b.current&&(b.current(),b.current=void 0)},[]);Object(c.a)(f,p),Object(a.n)(()=>{if(!l)return()=>{d.current&&(d.current.observer.disconnect(),d.current.callbacks.clear(),d.current=void 0)}},[l]);return{observe:Object(a.m)((a,c)=>{d.current||function(){const a=new Map,c=new Map,l=()=>{const e=Array.from(c.values());e.forEach(t=>{const n=a.get(t.target);n&&n(t,e)}),m.current&&m.current(e),c.clear()},u=t?r.g:n?r.a:void 0,f=u?u(l,t||n,!s):l,p=new IntersectionObserver(e=>{e.forEach(e=>{c.set(e.target,e)}),h.current?b.current=()=>{f()}:f()},{root:e.current,rootMargin:i?i+"px":void 0,threshold:o});d.current={observer:p,callbacks:a}}();const l=d.current;return l.observer.observe(a),c&&l.callbacks.set(a,c),()=>{c&&l.callbacks.delete(a),l.observer.unobserve(a)}},[l]),freeze:f,unfreeze:p}}function i(e,t,n){Object(a.n)(()=>t?t(e.current,n):void 0,[])}function o(e,t,n){const[r,c]=Object(a.r)(!t);return i(e,t,e=>{c(e.isIntersecting),n&&n(e)}),r}},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(48),s=n(31);t.a=(e,t=!1,n=r.ApiMediaFormat.BlobUrl,i,o)=>{const l=e?c.c(e):void 0,u=Object(s.a)();return Object(a.n)(()=>{if(!t&&e&&!l){const t=Date.now();c.b(e,n).then(()=>{const e=Date.now()-t;!o||e>=o?u():setTimeout(u,o-e)})}},[t,e,l,n,i,u,o]),l}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(19),s=n(6),i=n(5),o=n(37),l=n(3),u=n(94),d=n(101),m=n(122),h=n(148);t.a=Object(a.h)(Object(r.h)((e,{userId:t,forceShowSelf:n})=>{const{lastSyncTime:a}=e,r=Object(s.Db)(e,t);return{lastSyncTime:a,user:r,isSavedMessages:!n&&r&&r.isSelf,areMessagesLoaded:Boolean(Object(s.m)(e,t))}},(e,t)=>Object(l.l)(t,["loadFullUser","openMediaViewer"]))(({typingStatus:e,avatarSize:t="medium",status:n,withMediaViewer:r,withUsername:s,withFullInfo:l,withUpdatingStatus:b,noStatusOrTyping:f,user:p,isSavedMessages:g,areMessagesLoaded:O,lastSyncTime:v,loadFullUser:j,openMediaViewer:E})=>{const{id:y}=p||{},N=Object(i.Y)(p);Object(a.n)(()=>{l&&v&&y&&j({userId:y})},[y,j,v,l]);const T=Object(a.m)((e,n)=>{p&&n&&(e.stopPropagation(),E({avatarOwnerId:p.id,origin:"jumbo"===t?c.h.ProfileAvatar:c.h.MiddleHeaderAvatar}))},[p,t,E]),C=Object(u.a)();if(p)return a.a.createElement("div",{className:"ChatInfo"},a.a.createElement(d.a,{key:p.id,size:t,user:p,isSavedMessages:g,onClick:r?T:void 0}),a.a.createElement("div",{className:"info"},g?a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,C("SavedMessages"))):a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,N&&Object(o.a)(N)),p&&p.isVerified&&a.a.createElement(m.a,null)),(n||!g&&!f)&&(n?a.a.createElement("span",{className:"status"},n):b&&!O?a.a.createElement("span",{className:"status"},C("Updating")):p?e?a.a.createElement(h.a,{typingStatus:e}):a.a.createElement("div",{className:"status "+(Object(i.wb)(p)?"online":"")},s&&p.username&&a.a.createElement("span",{className:"handle"},p.username),a.a.createElement("span",{className:"user-status"},Object(i.Z)(p,C))):void 0)))}))},function(e,t,n){"use strict";var a=n(0),r=n(50);var c=n(8),s=n(43),i=n(29),o=n(52),l=n(94),u=n(25),d=n(113);n(140);t.a=e=>{const{title:t,className:n,isOpen:m,header:h,hasCloseButton:b,noBackdrop:f,children:p,onClose:g,onCloseAnimationEnd:O,onEnter:v}=e,{shouldRender:j,transitionClassNames:E}=Object(i.a)(m,O),y=Object(a.q)(null);Object(a.n)(()=>m?Object(r.a)({onEsc:g,onEnter:v}):void 0,[m,g,v]),Object(a.n)(()=>m&&y.current?function(e){function t(t){if("Tab"!==t.key)return;t.preventDefault(),t.stopPropagation();const n=Array.from(e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(!n.length)return;const a=n.findIndex(e=>e.isSameNode(document.activeElement));let r=0;a>=0&&(r=t.shiftKey?a>0?a-1:n.length-1:a{document.removeEventListener("keydown",t,!1)}}(y.current):void 0,[m]),Object(o.a)(([e])=>(document.body.classList.toggle("has-open-dialog",m),(m||!m&&void 0!==e)&&Object(s.b)(200),()=>{document.body.classList.remove("has-open-dialog")}),[m]);const N=Object(l.a)();if(!j)return;const T=Object(c.a)("Modal",n,E,f&&"transparent-backdrop");return a.a.createElement(d.a,null,a.a.createElement("div",{ref:y,className:T,tabIndex:-1,role:"dialog"},a.a.createElement("div",{className:"modal-container"},a.a.createElement("div",{className:"modal-backdrop",onClick:g}),a.a.createElement("div",{className:"modal-dialog"},h||(t?a.a.createElement("div",{className:"modal-header"},b&&a.a.createElement(u.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:N("Close"),onClick:g},a.a.createElement("i",{className:"icon-close"})),a.a.createElement("div",{className:"modal-title"},t)):void 0),a.a.createElement("div",{className:"modal-content custom-scroll"},p)))))}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(1),s=n(7),i=n(31),o=n(38),l=n(8),u=n(43);n(182);const d={slide:450,"mv-slide":400,"slide-fade":400,"zoom-fade":150,"scroll-slide":500,fade:150,"slide-layers":s.f?450:300,"push-slide":300,reveal:350},m=Symbol("CLEANED_UP");t.a=Object(r.h)(e=>{const{animationLevel:t}=e.settings.byKey;return{animationLevel:t}})(({ref:e,activeKey:t,name:n,direction:r="auto",renderCount:s,shouldRestoreHeight:h,shouldCleanup:b,id:f,className:p,onStart:g,onStop:O,children:v,animationLevel:j})=>{let E=Object(a.q)(null);e&&(E=e);const y=Object(a.q)({}),N=Object(o.a)(t),T=Object(a.q)(),C=Object(i.a)(),M=void 0!==N&&t!==N;!s&&M&&(y.current={[N]:y.current[N]}),y.current[t]=v,Object(a.o)(()=>{function e(){b&&(y.current={[N]:m},C())}const a=E.current,i=a.children;if(1===i.length&&!M)return void i[0].classList.add("active");const o=Array.from(a.childNodes);if(!M||!o.length)return;T.current&&(clearTimeout(T.current),T.current=void 0);const l=-1===r||"auto"===r&&N>t||"inverse"===r&&N{e instanceof HTMLElement&&(e.classList.remove("from","through","to"),e.classList.toggle("active",t===v))}),void e();if(o.forEach((e,t)=>{e instanceof HTMLElement&&(e.classList.remove("active"),e.classList.toggle("from",t===p),e.classList.toggle("through",t>p&&tv),e.classList.toggle("to",t===v))}),"scroll-slide"===n){const e=a.offsetWidth;a.scrollBy({left:v>p?e:-e,behavior:"smooth"})}j>0&&Object(u.b)(d[n]+c.c),requestAnimationFrame(()=>{a.classList.add("animating"),T.current=window.setTimeout(()=>{requestAnimationFrame(()=>{if(a.classList.remove("animating","backwards"),o.forEach((e,t)=>{e instanceof HTMLElement&&(e.classList.remove("from","through","to"),e.classList.toggle("active",t===v))}),"scroll-slide"===n&&(a.scrollLeft=t*a.offsetWidth),h){const e=a.querySelector(".active");e&&(e.style.height="auto",a.style.height=e.clientHeight+"px")}e(),O&&O()})},d[n]+c.c),g&&g()})},[t,N,M,r,n,g,O,s,h,b,j,C]),Object(a.o)(()=>{if(h){const e=E.current,t=e.querySelector(".active")||e.querySelector(".from");t&&(t.style.height="auto",e.style.height=t.clientHeight+"px")}},[h,v]);const w=y.current,I=Object.keys(s?new Array(s).fill(void 0):w).map(Number).map(e=>{const n=w[e];return"function"==typeof n?a.a.createElement("div",{key:e},n(e===t,e===N)):void 0}),S=Object(l.a)("Transition",p,0===j&&"scroll-slide"===n?"slide":n);return a.a.createElement("div",{ref:E,id:f,className:S},I)})},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(1),s=n(5),i=n(44),o=n(8),l=n(37),u=n(97),d=n(104),m=n(94);n(184);t.a=Object(a.h)(({className:e,size:t="large",chat:n,user:h,text:b,withOnlineStatus:f,isSavedMessages:p,lastSyncTime:g,onClick:O})=>{const v=h&&Object(s.ob)(h);let j;p||v||(h?j=Object(s.f)(h):n&&(j=Object(s.f)(n)));const E=Object(u.a)(j,!1,r.ApiMediaFormat.DataUri,g),{shouldRenderFullMedia:y,transitionClassNames:N}=Object(d.a)(E,"slow");Object(m.a)();let T="";if(p)T=a.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(v)T=a.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(y)T=a.a.createElement("img",{src:E,className:N+" avatar-media",alt:"",decoding:"async"});else if(h){const e=Object(s.Y)(h);T=e?Object(i.c)(e,2):void 0}else if(n){const e=Object(s.l)(n);T=e&&Object(i.c)(e,Object(s.kb)(n.id)?2:1)}else b&&(T=Object(i.c)(b,2));const C=!p&&h&&Object(s.wb)(h),M=Object(o.a)("Avatar size-"+t,e,"color-bg-"+Object(s.W)(h||n),p&&"saved-messages",v&&"deleted-account",f&&C&&"online",O&&"interactive",!p&&!y&&"no-photo"),w=Object(a.m)(e=>{O&&O(e,p||y)},[O,p,y]),I=(h||n)&&(h||n).id;return a.a.createElement("div",{className:M,onClick:w,"data-test-sender-id":c.E?I:void 0},"string"==typeof T?Object(l.a)(T,["jumbo"===t?"hq_emoji":"emoji"]):T)})},function(e,t,n){"use strict";var a=n(19),r=n(0),c=n(9),s=n(146);t.a=({ref:e,className:t,onLoadMore:n,onScroll:i,items:o,itemSelector:l=".ListItem",preloadBackwards:u=20,sensitiveArea:d=800,noScrollRestore:m=!1,noFastList:h,cacheBuster:b,children:f})=>{let p=Object(r.q)(null);e&&(p=e);const g=Object(r.q)({}),[O,v]=Object(r.p)(()=>n?[Object(c.a)(()=>n({direction:a.e.Backwards}),1e3,!0,!1),Object(c.a)(()=>n({direction:a.e.Forwards}),1e3,!0,!1)]:[],[n,o]);Object(r.n)(()=>{if(!O)return;if(u>0&&(!o||o.length{const e=p.current,t=g.current;if(t.listItemElements=e.querySelectorAll(l),m)return;let n;if(t.currentAnchor&&Array.from(t.listItemElements).includes(t.currentAnchor)){const{scrollTop:a}=e;n=a+(t.currentAnchor.getBoundingClientRect().top-t.currentAnchorTop)}else{const e=t.listItemElements[0];e&&e.offsetParent&&(t.currentAnchor=e,t.currentAnchorTop=e.getBoundingClientRect().top)}Object(s.a)(e,n),t.isScrollTopJustUpdated=!0},[m,l,o,b]);const j=Object(r.m)(e=>{if(v&&O){const{listItemElements:e,isScrollTopJustUpdated:t,currentAnchor:n,currentAnchorTop:a}=g.current;if(t)return void(g.current.isScrollTopJustUpdated=!1);const r=e.length,c=p.current,{scrollTop:i,scrollHeight:o,offsetHeight:l}=c,u=i<=(r?e[0].offsetTop:0)+d,m=(r?e[r-1].offsetTop+e[r-1].offsetHeight:o)-(i+l)<=d;let h=!1;if(u){const t=e[0];if(t){const e=t.getBoundingClientRect().top,r=n&&n.offsetParent&&n!==t?n.getBoundingClientRect().top:e;n&&void 0!==a&&r>a&&(g.current.currentAnchor=t,g.current.currentAnchorTop=e,h=!0,Object(s.a)(c),v())}}if(m){const t=e[r-1];if(t){const e=t.getBoundingClientRect().top,r=n&&n.offsetParent&&n!==t?n.getBoundingClientRect().top:e;n&&void 0!==a&&r{const n=Object(a.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";var a=n(0),r=n(29);const c={fast:200,slow:350};t.a=(e,t="fast",n=!1)=>{const s=Boolean(e),i=!Object(a.q)(s).current&&!n,[o,l]=Object(a.r)(!s),{shouldRender:u,transitionClassNames:d}=Object(r.a)(s,void 0,!i,t);return Object(a.n)(()=>{u&&(i?setTimeout(()=>{l(!1)},c[t]):l(!1))},[i,u,t]),{shouldRenderThumb:o,shouldRenderFullMedia:u,transitionClassNames:d}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return o})),n.d(t,"d",(function(){return l})),n.d(t,"a",(function(){return u})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return p})),n.d(t,"h",(function(){return g})),n.d(t,"k",(function(){return O})),n.d(t,"i",(function(){return v})),n.d(t,"l",(function(){return j})),n.d(t,"g",(function(){return E})),n.d(t,"e",(function(){return y}));var a=n(5),r=n(49),c=n(7),s=n(1);const i="(max-height: 640px)",o=parseInt(getComputedStyle(document.documentElement).fontSize,10),l=200,u={width:640,height:640},d={width:100,height:100};let m;function h(e,t,n){const a=t||n?1.625:0;return(function(e){const t=e?30:29;return c.f?(m||(m=Math.min(t,Math.floor(.69*window.innerWidth)/o)),m):t}(e)-a)*o}function b({width:e,height:t,fromOwnMessage:n,isForwarded:a,isWebPagePhoto:r,isGif:c}){const s=t/e;return y(h(n,a,r),function(e,t){return e&&t&&t>=.75&&t<=1.25?20*o:27*o}(c,s),e,t)}function f(e,t){const n=window.matchMedia(i),{width:a,height:c}=r.a.get();let s=t&&n.matches?10:8.25;return e&&(s=n.matches?10:15),{width:a,height:c-s*o}}function p(e,t,n,r){const{width:c,height:s}=Object(a.S)(e)||d;return b({width:c,height:s,fromOwnMessage:t,isForwarded:n,isWebPagePhoto:r})}function g(e,t,n){const{width:r,height:c}=Object(a.ab)(e)||d;return b({width:r,height:c,fromOwnMessage:t,isForwarded:n,isGif:e.isGif})}function O(){return{width:2*o,height:2*o}}function v(e){return e?{width:3*o,height:3*o}:{width:3.375*o,height:3.375*o}}function j(e){const{width:t}=e;let{height:n}=e;"1258816259753933"===e.id&&(n=t);const a=n&&t&&n/t,r=(c.f?s.ub:s.tb)*o,i=a?r*a:r;return a&&i>r?{width:Math.round(r/a),height:r}:{width:r,height:i}}function E({width:e,height:t},n,a=!1){const{width:r,height:c}=f(n,a);return y(r,c,e,t)}function y(e,t,n,a){const r=a/n,c=Math.min(n,e);return Math.round(c*r)>t?{width:Math.round(t/r),height:t}:{width:c,height:Math.round(c*r)}}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(9),s=n(8),i=n(43),o=n(127);let l,u;async function d(){return l||(l=n.e(6).then(n.bind(null,181)),u=(await l).default),l}setTimeout(d,5e3);t.a=Object(a.h)(({className:e,id:t,animationData:n,play:l,playSegment:m,speed:h,noLoop:b,size:f,quality:p,isLowPriority:g,onLoad:O})=>{const[v,j]=Object(a.r)(),E=Object(a.q)(null),y=Object(a.q)(!1),N=Object(a.q)(!1),T=Object(a.q)();T.current=l;const C=Object(a.q)();C.current=m,Object(a.n)(()=>{if(v||!n)return;const e=()=>{if(!E.current)return;const e=new u(t,E.current,n,{noLoop:b,size:f,quality:p,isLowPriority:g},O);h&&e.setSpeed(h),j(e)};u?e():d().then(()=>{Object(c.b)(()=>{E.current&&e()})})},[v,n,t,g,b,O,p,f,h]),Object(a.n)(()=>()=>{v&&v.destroy()},[v]);const M=Object(a.m)((e=!1)=>{v&&(T.current||C.current)&&(C.current?v.playSegment(C.current):e?v.goToAndPlay(0):v.play())},[v]),w=Object(a.m)(()=>{v&&v.pause()},[v]),I=Object(a.m)(()=>{N.current=!0,v&&(y.current||(y.current=v.isPlaying()),w())},[v,w]),S=Object(a.m)(()=>{y.current&&M(),y.current=!1,N.current=!1},[M]),L=Object(a.m)(()=>{Object(c.b)(S)},[S]);Object(a.n)(()=>{v&&(l||m?N.current?y.current=!0:M(b):N.current?y.current=!1:w())},[v,l,m,b,M,w]),Object(i.a)(I,S),Object(o.a)(I,L);const k=Object(s.a)("AnimatedSticker",e,r.d&&l&&"is-playing"),A=f?`width: ${f}px; height: ${f}px;`:void 0;return a.a.createElement("div",{ref:E,className:k,style:A})})},function(e,t,n){"use strict";var a=n(0),r=n(94),c=n(99),s=n(25);t.a=Object(a.h)(({isOpen:e,onClose:t,onCloseAnimationEnd:n,header:i,text:o,textParts:l,confirmLabel:u="Confirm",confirmHandler:d,confirmIsDestructive:m,isButtonsInOneRow:h})=>{const b=Object(r.a)();return a.a.createElement(c.a,{className:"confirm",header:i,isOpen:e,onClose:t,onCloseAnimationEnd:n,onEnter:d},o&&o.split("\\n").map(e=>a.a.createElement("p",null,e)),l,a.a.createElement("div",{className:h?"dialog-buttons mt-2":""},a.a.createElement(s.a,{className:"confirm-dialog-button",isText:!0,onClick:d,color:m?"danger":"primary"},u),a.a.createElement(s.a,{className:"confirm-dialog-button",isText:!0,onClick:t},b("Cancel"))))})},function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(29);n(238);t.a=Object(a.h)(({text:e="Nothing found."})=>{const{transitionClassNames:t}=Object(c.a)(!0);return a.a.createElement("div",{className:Object(r.a)("NothingFound",t)},e)})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(0),r=n(103),c=n(31);function s(e,t){const n=void 0===t,s=Object(a.q)(n),i=Object(a.q)(),o=Object(c.a)();return Object(r.a)(()=>{n||(s.current=!1,i.current&&(clearTimeout(i.current),i.current=void 0))},e),Object(a.n)(()=>{if(n||s.current)return;const e=()=>{s.current=!0,o()};t>0?i.current=window.setTimeout(e,t):e()},e),s.current}},function(e,t,n){"use strict";var a=n(0),r=n(8);n(191);t.a=({children:e,className:t,onClick:n})=>{const c=Object(a.m)(e=>{e.preventDefault(),n(e)},[n]);return a.a.createElement("a",{href:"#",className:Object(r.a)("Link",t),onClick:n?c:void 0},e)}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(4),s=n(9),i=n(48),o=n(31);t.a=(e,t=!1,n=c.ApiMediaFormat.BlobUrl,l,u)=>{const d=e?i.c(e):void 0,m=n===c.ApiMediaFormat.Stream||r.h&&n===c.ApiMediaFormat.Progressive,h=Object(o.a)(),[b,f]=Object(a.r)(d&&!m?1:0),p=Object(a.q)(),g=Object(a.p)(()=>Object(s.g)(e=>{(!u||Date.now()-p.current>u)&&f(e)},500,!0),[u]);return Object(a.n)(()=>{!t&&e&&(d?m&&setTimeout(()=>{f(.75)},1500):(f(0),p.current&&i.a(g),p.current=Date.now(),i.b(e,n,g).then(()=>{const e=Date.now()-p.current;p.current=void 0,!u||e>=u?h():setTimeout(h,u-e)})))},[t,e,d,n,l,h,m,u,g]),Object(a.n)(()=>{t&&p.current&&(i.a(g),f(0))},[g,t]),{mediaData:d,downloadProgress:b}}},function(e,t,n){"use strict";var a=n(0),r=n(8);n(208);const c={s:22,m:25,l:28,xl:20};t.a=Object(a.h)(({progress:e=0,size:t="l",square:n,transparent:s,noCross:i,onClick:o})=>{const l=c[t],u=l-4,d=l-1,m=2*u*Math.PI,h=Object(a.q)(null);Object(a.n)(()=>{if(!h.current)return;const t=h.current.firstElementChild,n=m-Math.min(Math.max(.05,e),1)*m;t?t.firstElementChild.setAttribute("stroke-dashoffset",n.toString()):h.current.innerHTML=`\n \n `},[h,m,d,u,e]);const b=Object(r.a)("ProgressSpinner size-"+t,s&&"transparent",n&&"square",i&&"no-cross");return a.a.createElement("div",{ref:h,className:b,onClick:o})})},function(e,t,n){"use strict";var a=n(0),r=n(57);t.a=({containerId:e,className:t,children:n})=>{const c=Object(a.q)(document.createElement("div"));return Object(a.o)(()=>{const n=document.querySelector(e||"#portals");if(!n)return;const a=c.current;return t&&a.classList.add(t),n.appendChild(a),()=>{r.a.render(void 0,a),n.removeChild(a)}},[t,e]),r.a.render(n,c.current)}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(19),s=n(5),i=n(6),o=n(37),l=n(3),u=n(94),d=n(101),m=n(122),h=n(148);t.a=Object(a.h)(Object(r.h)((e,{chatId:t})=>{const{lastSyncTime:n}=e,a=Object(i.f)(e,t);return{lastSyncTime:n,chat:a,onlineCount:a?Object(i.n)(e,a):void 0,areMessagesLoaded:Boolean(Object(i.m)(e,t))}},(e,t)=>Object(l.l)(t,["loadFullChat","openMediaViewer"]))(({typingStatus:e,avatarSize:t="medium",withMediaViewer:n,withUsername:r,withFullInfo:i,withUpdatingStatus:l,withChatType:b,chat:f,onlineCount:p,areMessagesLoaded:g,lastSyncTime:O,loadFullChat:v,openMediaViewer:j})=>{const E=f&&Object(s.mb)(f),{id:y,isMin:N,isRestricted:T}=f||{};Object(a.n)(()=>{y&&!N&&i&&O&&v({chatId:y})},[y,N,O,i,v,E]);const C=Object(a.m)((e,n)=>{f&&n&&(e.stopPropagation(),j({avatarOwnerId:f.id,origin:"jumbo"===t?c.h.ProfileAvatar:c.h.MiddleHeaderAvatar}))},[f,t,j]),M=Object(u.a)();if(f)return a.a.createElement("div",{className:"ChatInfo"},a.a.createElement(d.a,{key:f.id,size:t,chat:f,onClick:n?C:void 0}),a.a.createElement("div",{className:"info"},a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,Object(o.a)(Object(s.l)(f))),f.isVerified&&a.a.createElement(m.a,null)),function(){if(l&&!g&&!T)return a.a.createElement("span",{className:"status"},M("Updating"));if(!f)return;if(e)return a.a.createElement(h.a,{typingStatus:e});if(b)return a.a.createElement("div",{className:"status"},M(Object(s.m)(f)));const t=r?f.username:void 0,n=function(e,t){const n=t(Object(s.m)(e)),{membersCount:a}=e;if(e.isRestricted)return"Channel"===n?"channel is inaccessible":"group is inaccessible";if(!a)return n;return t("Channel"===n?"Subscribers":"Members",a,"i")}(f,M),c=p?", "+M("OnlineCount",p,"i"):void 0;return a.a.createElement("div",{className:"status"},t&&a.a.createElement("span",{className:"handle"},t),a.a.createElement("span",{className:"group-status"},n),c&&a.a.createElement("span",{className:"online-status"},c))}()))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return l}));var a=n(19),r=n(43),c=n(9),s=n(55);let i=!1;function o(e,t,n,o=0,l=1500,u,d,m){if(u===a.b.Static)return void t.scrollIntoView({block:n});const{offsetTop:h}=t;if(void 0===u){const t=h-e.scrollTop;t<-l?e.scrollTop+=t+l:t>l&&(e.scrollTop+=t-l)}else u===a.b.Up?e.scrollTop=h+l:u===a.b.Down&&(e.scrollTop=Math.max(0,h-l));i=!0,Object(c.b)(()=>{Object(r.b)(600),function(e,t,n,a=0,r,c){const{offsetTop:o,offsetHeight:l}=t,{scrollTop:u,offsetHeight:d,scrollHeight:m}=e,h=!c&&e.dataset.normalHeight?Number(e.dataset.normalHeight):d;let b;switch(n){case"start":b=o-a-u;break;case"end":b=o+l+a-(u+h);break;case"nearest":case"center":b=l0){const e=m-(u+h);b=Math.min(b,e)}const f=e.scrollTop+b,p=r||250+Math.abs(b)/1500*350,g=Date.now();Object(s.b)(()=>{const t=Math.min((Date.now()-g)/p,1),n=b*(1-function(e){return 1-(1-e)**3.5}(t));return e.scrollTop=Math.round(f-n),i=t<1,i})}(e,t,n,o,d,m)})}function l(){return i}},,function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(20);n(215);var s=Object(a.h)(({id:e,label:t,subLabel:n,value:s,name:i,checked:o,disabled:l,hidden:u,isLoading:d,onChange:m})=>{const h=Object(r.a)("Radio",l&&"disabled",u&&"hidden-widget",d&&"loading");return a.a.createElement("label",{className:h},a.a.createElement("input",{type:"radio",name:i,value:s,id:e,checked:o,onChange:m,disabled:l||u}),a.a.createElement("div",{className:"Radio-main"},a.a.createElement("span",{className:"label"},t),n&&a.a.createElement("span",{className:"subLabel"},n)),d&&a.a.createElement(c.a,null))});t.a=Object(a.h)(({id:e,name:t,options:n,selected:r,disabled:c,loadingOption:i,onChange:o})=>{const l=Object(a.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]);return a.a.createElement("div",{id:e,className:"radio-group"},n.map(e=>a.a.createElement(s,{name:t,label:e.label,subLabel:e.subLabel,value:e.value,checked:e.value===r,hidden:e.hidden,disabled:c,isLoading:i?i===e.value:void 0,onChange:l})))})},function(e,t,n){"use strict";var a=n(0),r=n(19),c=n(3),s=n(31),i=n(38);function o(e,t=0,n,a){const{length:c}=e,s=e.indexOf(t),i=n===r.e.Forwards?s:s+1||c,o=Math.max(0,i-a),l=i+a-1,u=e.slice(Math.max(0,o),l+1);let d,m;switch(n){case r.e.Forwards:d=i>0,m=o>=0;break;case r.e.Backwards:d=i{const d=Object(a.q)(),m=Object(a.q)((()=>{if(!t||d.current)return;const{newViewportIds:e}=o(t,t[0],r.e.Forwards,l);return e})()),h=Object(s.a)(),b=Object(i.a)(t),f=Object(i.a)(n);if(t&&!n&&(t!==b||n!==f)){const{offsetId:e=t[0],direction:n=r.e.Forwards}=d.current||{},{newViewportIds:a}=o(t,e,n,l);m.current&&Object(c.a)(m.current,a)||(m.current=a)}Object(a.n)(()=>{if(t&&!n&&e&&u){const t=m.current;e({offsetId:t[t.length-1]})}},[t,n,e,u]);const p=Object(a.m)(({direction:n})=>{const a=m.current,s=a?n===r.e.Backwards?a[a.length-1]:a[0]:void 0;if(!t)return void(e&&e({offsetId:s}));d.current={...d.current,direction:n,offsetId:s};const{newViewportIds:i,areSomeLocal:u,areAllLocal:b}=o(t,s,n,l);!u||a&&Object(c.a)(a,i)||(m.current=i,h()),!b&&e&&e({offsetId:s})},[t,l,e,h]);return n?[t]:[m.current,p]}},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(1),s=n(105),i=n(96),o=n(97),l=n(104),u=n(28),d=n(106);n(213);t.a=({sticker:e,isInline:t=!1,observeIntersection:n,lastSyncTime:m})=>{const h=Object(a.q)(null),[b,f]=Object(u.a)(),p="sticker"+e.id,g=Object(i.b)(h,n),O=Object(o.a)(p+"?size=m",!g,r.ApiMediaFormat.BlobUrl,m),{transitionClassNames:v}=Object(l.a)(O,"slow"),j=Object(o.a)(p,!g,r.ApiMediaFormat.Lottie,m),E=Boolean(j),[y,N]=Object(a.r)(String(Math.random())),T=Object(a.m)(()=>{N(String(Math.random()))},[]);let C;C=t?.5*Object(s.l)(e).width:c.zb;const M=`width: ${C}px; height: ${C}px;`;return a.a.createElement("div",{ref:h,className:"AnimatedEmoji media-inner",style:M,onClick:T},O&&!b&&a.a.createElement("img",{src:O,className:v,alt:""}),E&&a.a.createElement(d.a,{key:p,id:p,animationData:j,size:C,quality:1,play:g&&y,noLoop:!0,onLoad:f}))}},,function(e,t,n){"use strict";let a;n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return r})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Left=2]="Left",e[e.Right=3]="Right"}(a||(a={}));function r(e,t){let n,r=!1;function c(e){t.excludedClosestSelector&&(e.target.matches(t.excludedClosestSelector)||e.target.closest(t.excludedClosestSelector))||(n=e,"mousedown"===e.type?(document.addEventListener("mousemove",i),document.addEventListener("mouseup",s)):"touchstart"===e.type&&(document.addEventListener("touchmove",i),document.addEventListener("touchend",s),document.addEventListener("touchcancel",s),"touches"in e&&(void 0===e.pageX&&(e.pageX=e.touches[0].pageX),void 0===e.pageY&&(e.pageY=e.touches[0].pageY))),document.body.classList.add("no-selection"),t.withCursor&&document.body.classList.add("cursor-grabbing"),t.onCapture&&t.onCapture(e))}function s(e){n&&(t.withCursor&&document.body.classList.remove("cursor-grabbing"),document.body.classList.remove("no-selection"),document.removeEventListener("mouseup",s),document.removeEventListener("mousemove",i),document.removeEventListener("touchcancel",s),document.removeEventListener("touchend",s),document.removeEventListener("touchmove",i),n=void 0,r?t.onRelease&&t.onRelease(e):t.onClick&&t.onClick(e)),r=!1}function i(e){if(n){"touchmove"===e.type&&"touches"in e&&(void 0===e.pageX&&(e.pageX=e.touches[0].pageX),void 0===e.pageY&&(e.pageY=e.touches[0].pageY));const c=e.pageX-n.pageX,s=e.pageY-n.pageY;(Math.abs(c)>=15||Math.abs(s)>=15)&&(r=!0),t.onDrag&&t.onDrag(e,n,{dragOffsetX:c,dragOffsetY:s}),t.onSwipe&&function(e,t,n,r){const c=Math.abs(t),s=Math.abs(n);if(t&&n){if(Math.max(c,s)/Math.min(c,s)<2)return}c>=50?r(e,t<0?a.Left:a.Right):s>=50&&r(e,n<0?a.Up:a.Down)}(e,c,s,t.onSwipe)}}return e.addEventListener("mousedown",c),e.addEventListener("touchstart",c,{passive:!0}),()=>{e.removeEventListener("mousedown",c),e.removeEventListener("touchstart",c)}}},function(e,t,n){"use strict";var a=n(0);n(192);t.a=()=>a.a.createElement("span",{className:"VerifiedIcon"})},function(e,t,n){"use strict";var a=n(0),r=n(9),c=n(150);t.a=(e=!1)=>{const[t,n]=Object(a.r)(!e),[s,i]=Object(a.r)(0),o=Object(a.p)(()=>Object(r.a)(n,200,!1,!0),[]),l=Object(a.m)(e=>{const t=e.currentTarget;Object(c.a)(t)||(t.buffered.length&&i(t.buffered.end(0)/t.duration),o(t.readyState>=3||t.currentTime>0))},[o]);return{isBuffered:t,bufferedProgress:s,bufferingHandlers:{onLoadedData:l,onPlaying:l,onLoadStart:l,onPause:l,onTimeUpdate:l,onProgress:l},checkBuffering(e){o(e.readyState>=3)}}}},function(e,t,n){"use strict";function a(e,t){if(!t&&e===document.activeElement)return;const n=window.getSelection(),a=document.createRange();e.lastChild&&e.lastChild.nodeValue?(a.setStart(e.lastChild,e.lastChild.nodeValue.length),n.removeAllRanges(),n.addRange(a)):e.focus()}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(4),r=n(7);const c={B:a.ApiMessageEntityTypes.Bold,STRONG:a.ApiMessageEntityTypes.Bold,I:a.ApiMessageEntityTypes.Italic,EM:a.ApiMessageEntityTypes.Italic,U:a.ApiMessageEntityTypes.Underline,S:a.ApiMessageEntityTypes.Strike,STRIKE:a.ApiMessageEntityTypes.Strike,DEL:a.ApiMessageEntityTypes.Strike,CODE:a.ApiMessageEntityTypes.Code,PRE:a.ApiMessageEntityTypes.Pre,BLOCKQUOTE:a.ApiMessageEntityTypes.Blockquote};function s(e){const t=document.createElement("div");t.innerHTML=function(e){let t=e.slice(0);r.c||(t=t.replace(/]+alt="([^"]+)"[^>]*>/gm,"$1"));return t=t.replace(/<\/?span([^>]*)?>/g,""),t=t.replace(/ /g," "),t=t.replace(/]*)?>/g,"\n"),t=t.replace(/<\/div>(\s*)
/g,"\n"),t=t.replace(/
/g,"\n"),t=t.replace(/<\/div>/g,""),t=t.replace(/^`{3}(.*[\n\r][^]*?^)`{3}/gm,"
$1
"),t=t.replace(/[`]{3}([^`]+)[`]{3}/g,"
$1
"),t=t.replace(/[`]{1}([^`\n]+)[`]{1}/g,"$1"),t=t.replace(/[*]{2}([^*\n]+)[*]{2}/g,"$1"),t=t.replace(/[*]{1}([^*\n]+)[*]{1}/g,"$1"),t=t.replace(/[~]{2}([^~\n]+)[~]{2}/g,"$1"),t}(e);const n=t.innerText.trim().replace(/\u200b+/g,"").slice(0,4096);let s=0,i=0;const o=[];function l(e){const{index:t,entity:r}=function(e,t,n){const r=function(e){if(c[e.nodeName])return c[e.nodeName];if("A"===e.nodeName){const t=e;return t.dataset.entityType===a.ApiMessageEntityTypes.MentionName?a.ApiMessageEntityTypes.MentionName:t.href.startsWith("mailto:")?a.ApiMessageEntityTypes.Email:t.href.startsWith("tel:")?a.ApiMessageEntityTypes.Phone:t.href!==t.textContent?a.ApiMessageEntityTypes.TextUrl:a.ApiMessageEntityTypes.Url}if("SPAN"===e.nodeName)return e.dataset.entityType;return}(e);if(!r||!e.textContent)return{index:n,entity:void 0};const s=t.indexOf(e.textContent,n),i=s>=0?s:n,o=t.substring(0,i).length,{length:l}=t.substring(i,i+e.textContent.length);let u,d;r===a.ApiMessageEntityTypes.TextUrl&&(u=e.href);r===a.ApiMessageEntityTypes.MentionName&&(d=Number(e.dataset.userId));return{index:i,entity:{type:r,offset:o,length:l,...u&&{url:u},...d&&{userId:d}}}}(e,n,s);r?(s=t,o.push(r)):e.textContent&&(s+=e.textContent.length),e.hasChildNodes()&&i<=3&&(i+=1,Array.from(e.childNodes).forEach(l))}return Array.from(t.childNodes).forEach(e=>{i=1,l(e)}),{text:n,entities:o.length?o:void 0}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var a=n(0),r=n(29),c=n(8),s=n(42),i=n(38),o=n(28);n(203);var l=Object(a.h)(({isQuick:e,onFileSelect:t})=>{const[n,r,s]=Object(o.a)(),i=Object(c.a)("DropTarget",n&&"hovered");return a.a.createElement("div",{className:i,onDrop:t,onDragEnter:()=>{r()},onDragLeave:e=>{const{relatedTarget:t}=e;t&&e.stopPropagation(),s()}},a.a.createElement("div",{className:"target-content"},a.a.createElement("div",{className:"icon icon-"+(e?"photo":"document")}),a.a.createElement("div",{className:"title"},"Drop files here to send them"),a.a.createElement("div",{className:"description"},e?"in a quick way":"without compression")))});n(204);let u;!function(e){e.None="none",e.Document="document",e.QuickFile="quick_file"}(u||(u={}));t.b=Object(a.h)(({isOpen:e,withQuick:t,onHide:n,onFileSelect:o})=>{const u=Object(a.q)(null),d=Object(i.a)(t),{shouldRender:m,transitionClassNames:h}=Object(r.a)(e);Object(a.n)(()=>e?Object(s.a)(n):void 0,[e,n]);const b=Object(a.m)(e=>{const{dataTransfer:t}=e;t.files&&t.files.length>0&&(n(),o(Array.from(t.files),!1))},[o,n]),f=Object(a.m)(e=>{const{dataTransfer:t}=e;t.files&&t.files.length>0&&(n(),o(Array.from(t.files),!0))},[o,n]),p=Object(a.m)(e=>{e.stopPropagation();const{target:t,relatedTarget:a}=e;t.matches(".DropTarget, .DropArea")&&!a&&(u.current=window.setTimeout(()=>{n()},150))},[n]);if(!m)return;const g=Object(c.a)("DropArea",h);return a.a.createElement("div",{className:g,onDragLeave:p,onDragOver:()=>{u.current&&window.clearTimeout(u.current)},onDrop:n},a.a.createElement(l,{onFileSelect:b}),(t||d)&&a.a.createElement(l,{onFileSelect:f,isQuick:!0}))})},function(e,t,n){"use strict";var a=n(0);t.a=(e,t)=>{Object(a.n)(()=>(document.hasFocus()||e(),window.addEventListener("blur",e),window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t),window.removeEventListener("blur",e)}),[e,t])}},,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(37),o=n(8),l=n(94),u=n(101);n(185);t.a=Object(a.h)(Object(r.h)((e,{chatOrUserId:t})=>{if(!t)return{};return{chat:t?Object(c.f)(e,t):void 0,user:Object(s.kb)(t)?Object(c.Db)(e,t):void 0}})(({icon:e,title:t,isMinimized:n,canClose:r,onClick:c,clickArg:d,chat:m,user:h,className:b})=>{let f,p;if(Object(l.a)(),e&&t)f=a.a.createElement("div",{className:"item-icon"},a.a.createElement("i",{className:"icon-"+e})),p=t;else if(m||h){f=a.a.createElement(u.a,{chat:m,user:h,size:"small",isSavedMessages:h&&h.isSelf});const e=!m||h&&!h.isSelf?Object(s.X)(h):Object(s.l)(m,h);p=e?Object(i.a)(e):void 0}const g=Object(o.a)("PickerSelectedItem",b,n&&"minimized",r&&"closeable");return a.a.createElement("div",{className:g,onClick:()=>c(d),title:n?p:void 0},f,!n&&a.a.createElement("div",{className:"item-name"},p),r&&a.a.createElement("div",{className:"item-remove"},a.a.createElement("i",{className:"icon-close"})))}))},function(e,t,n){"use strict";var a=n(0);t.a=(e,t)=>{Object(a.n)(()=>{const t=e.current;if(t)return t.addEventListener("wheel",n,{passive:!0}),()=>{t.removeEventListener("wheel",n)};function n(e){e.deltaX||(t.scrollLeft+=e.deltaY/4)}},[e,t])}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(9);t.a=(e,t,n,s)=>{const{loadMessage:i}=Object(r.d)(),o=Object(a.p)(()=>{const n=Object(c.g)(i,500,!0);return()=>{n({chatId:e,messageId:t,replyOriginForId:s})}},[i,e,t,s]);Object(a.n)(()=>{t&&!n&&o()})}},function(e,t,n){"use strict";var a=n(0),r=n(7);let c=0;t.a=(e,t)=>{const[n,s]=Object(a.r)(!1),[i,o]=Object(a.r)(void 0),l=Object(a.m)(e=>{t||2!==e.button||document.body.classList.add("no-selection")},[t]),u=Object(a.m)(e=>{t||(e.preventDefault(),document.body.classList.remove("no-selection"),i||(document.body.classList.remove("no-selection"),0===c&&document.body.classList.add("has-context-menu"),c++,s(!0),o({x:e.clientX,y:e.clientY})))},[t,i]),d=Object(a.m)(()=>{s(!1)},[]),m=Object(a.m)(()=>{o(void 0),document.body.classList.remove("no-selection"),setTimeout(()=>{c--,0===c&&document.body.classList.remove("has-context-menu")},200)},[]);return Object(a.n)(()=>{if(t||!r.k)return;const n=e.current;if(!n)return;let a;const c=()=>{a&&(clearTimeout(a),a=void 0)},l=e=>{t||r.f&&window.document.body.classList.contains("enable-symbol-menu-transforms")||(c(),a=window.setTimeout(()=>(e=>{c();const{clientX:t,clientY:a}=e.touches[0];i||(n.addEventListener("touchend",(function e(t){n.removeEventListener("touchend",e,!0),t.stopImmediatePropagation(),t.preventDefault(),t.stopPropagation()}),!0),document.body.classList.add("no-selection"),s(!0),o({x:t,y:a}))})(e),250))};return n.addEventListener("touchstart",l,{passive:!0}),n.addEventListener("touchcancel",c,!0),n.addEventListener("touchend",c,!0),n.addEventListener("touchmove",c,{passive:!0}),()=>{c(),n.removeEventListener("touchstart",l),n.removeEventListener("touchcancel",c,!0),n.removeEventListener("touchend",c,!0),n.removeEventListener("touchmove",c)}},[i,t,e]),{isContextMenuOpen:n,contextMenuPosition:i,handleBeforeContextMenu:l,handleContextMenu:u,handleContextMenuClose:d,handleContextMenuHide:m}}},function(e,t,n){"use strict";function a(e,t){return t-Math.floor(t/e)*e}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a=n(1);t.a=e=>{e.play().catch(e=>{a.o&&console.warn(e)})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return m}));var a=n(0),r=n(2),c=n(4),s=n(5),i=n(37),o=n(68),l=n(51);function u(e,t,n){const a=e.content.text;if(!a||!a.text){const t=Object(s.N)(e);return t?[t]:void 0}const{text:r,entities:c}=a;return m(r,c,t,n)}function d(e){const t=new Set,n=[];return e.forEach((a,r)=>{if(t.has(r))return;const c=function e(t,n,a,r){const{offset:c,length:s}=t,i=new Set([n]);if(r.has(n))return;const o=a.filter((e,t)=>t>n&&e.offset>=c&&e.offsete(t,a.indexOf(t),a,r)).filter(Boolean);return o.forEach(e=>e.organizedIndexes.forEach(e=>i.add(e))),{entity:t,organizedIndexes:i,nestedEntities:o}}(a,r,e,t);c&&(c.organizedIndexes.forEach(e=>{t.add(e)}),n.push(c))}),n}function m(e,t,n,r,s){if(!t||!t.length)return h(e,n,r,s);const u=[];let m=!1;const g=d(t);function O(t,u,d,g){const v=[],{entity:j,nestedEntities:E}=d,{offset:y,length:N,type:T}=j;let C=e.substring(t,y);const M=C.length;C&&(m&&C.length>0&&"\n"===C[0]&&(C=C.substr(1),m=!1),C&&v.push(...h(C,n,r,s)));const w=t+M,I=w+N;let S=e.substring(y,y+N);const L=[];if(m&&S.length>0&&"\n"===S[0]&&(S=S.substr(1),m=!1),T===c.ApiMessageEntityTypes.Pre&&(m=!0),E.length){let e=w;E.forEach((t,n)=>{const{renderResult:a,entityEndIndex:r}=O(e,I,t,n===E.length-1);L.push(...a),e=r})}const k=s?function(e,t,n){const a="string"==typeof t&&t,r=n.length?n.join(""):Object(i.a)(t,["emoji_html","br_html"]).join("");if(!a)return r;switch(e.type){case c.ApiMessageEntityTypes.Bold:return`${r}`;case c.ApiMessageEntityTypes.Italic:return`${r}`;case c.ApiMessageEntityTypes.Underline:return`${r}`;case c.ApiMessageEntityTypes.Code:return`${r}`;case c.ApiMessageEntityTypes.Pre:return`\`\`\`
${r}
\`\`\``;case c.ApiMessageEntityTypes.Strike:return`${r}`;case c.ApiMessageEntityTypes.MentionName:return`${r}`;case c.ApiMessageEntityTypes.Url:case c.ApiMessageEntityTypes.TextUrl:return`${r}`;default:return r}}(j,S,L):function(e,t,n){const r="string"==typeof t&&t,s=n.length?n:t;if(!r)return h(s);switch(e.type){case c.ApiMessageEntityTypes.Bold:return a.a.createElement("strong",null,h(s));case c.ApiMessageEntityTypes.Blockquote:return a.a.createElement("blockquote",null,h(s));case c.ApiMessageEntityTypes.BotCommand:return a.a.createElement("a",{onClick:f,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Hashtag:case c.ApiMessageEntityTypes.Cashtag:return a.a.createElement("a",{onClick:p,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Code:return a.a.createElement("code",{className:"text-entity-code"},h(s));case c.ApiMessageEntityTypes.Email:return a.a.createElement("a",{href:"mailto:"+r,target:"_blank",rel:"noopener noreferrer",className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Italic:return a.a.createElement("em",null,h(s));case c.ApiMessageEntityTypes.MentionName:return a.a.createElement(o.a,{userId:e.userId},h(s));case c.ApiMessageEntityTypes.Mention:return a.a.createElement(o.a,{username:r},h(s));case c.ApiMessageEntityTypes.Phone:return a.a.createElement("a",{href:"tel:"+r,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Pre:return a.a.createElement("pre",{className:"text-entity-pre"},h(s));case c.ApiMessageEntityTypes.Strike:return a.a.createElement("del",null,h(s));case c.ApiMessageEntityTypes.TextUrl:case c.ApiMessageEntityTypes.Url:return a.a.createElement(l.a,{url:b(r,e),text:r},h(s));case c.ApiMessageEntityTypes.Underline:return a.a.createElement("ins",null,h(s));default:return h(s)}}(j,S,L);if(Array.isArray(k)?v.push(...k):v.push(k),g&&I0&&"\n"===t[0]&&(t=t.substring(1)),t&&v.push(...h(t,n,r,s))}return{renderResult:v,entityEndIndex:I}}let v=0;return g.forEach((t,n)=>{const{renderResult:a,entityEndIndex:r}=O(v,e.length,t,n===g.length-1);u.push(...a),v=r}),u}function h(e,t,n,a){if(Array.isArray(e)){const r=[];return e.forEach(e=>{r.push(...h(e,t,n,a))}),r}if(a)return Object(i.a)(e,["escape_html","emoji_html","br_html"]);const r=n?"hq_emoji":"emoji";return t?Object(i.a)(e,[r,"br","highlight"],{highlight:t}):Object(i.a)(e,[r,"br"])}function b(e,t){const{type:n,url:a}=t;return n===c.ApiMessageEntityTypes.TextUrl&&a?a:e}function f(e){Object(r.d)().sendBotCommand({command:e.currentTarget.innerText})}function p(e){Object(r.d)().setLocalTextSearchQuery({query:e.currentTarget.innerText}),Object(r.d)().searchTextMessagesLocal()}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var a=n(0),r=n(169),c=n(14),s=n(31);const i=new Map;function o(e,t=!1,n){const o=Object(a.q)(e?i.get(e):void 0),l=Object(a.q)(),u=Object(s.a)();return l.current&&t&&(clearTimeout(l.current),l.current=void 0),Object(a.n)(()=>{if(!e||o.current||t)return;const a=new Image;a.onload=()=>{const t=Object(c.f)(a);Object(r.a)(t.getContext("2d"),0,0,t.width,t.height,2,2);const n=t.toDataURL();o.current=n,u(),i.size>=1e3&&i.clear(),i.set(e,n)},n?l.current=window.setTimeout(()=>{a.src=e},n):a.src=e},[e,n,u,t]),o.current}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var a=n(0),r=n(9);function c(e,t){Object(a.n)(()=>{const t=e.current;return()=>{t&&Object(r.b)(()=>{t.pause(),t.src="",t.load()})}},t)}},,,function(e,t,n){},,,function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return i}));var a=n(1);const r=navigator.clipboard&&window.ClipboardItem,c=document.createElement("textarea");c.setAttribute("readonly",""),c.tabIndex=-1,c.className="visually-hidden";const s=e=>{c.value=e,document.body.appendChild(c);const t=document.getSelection();if(t){const e=t.rangeCount>0&&t.getRangeAt(0);c.select(),document.execCommand("copy"),e&&(t.removeAllRanges(),t.addRange(e))}document.body.removeChild(c)},i=e=>{const t=document.createElement("canvas"),n=t.getContext("2d"),a=new Image;a.onload=e=>{if(n&&e.currentTarget){const a=e.currentTarget;t.width=a.width,t.height=a.height,n.drawImage(a,0,0,a.width,a.height),t.toBlob(o,"image/png",1)}},a.src=e};async function o(e){if(e&&r)try{await navigator.clipboard.write([new window.ClipboardItem({[e.type]:e})])}catch(e){a.o&&console.error(e)}}},function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(28),s=n(94),i=n(16),o=n(25);n(183);t.a=Object(a.h)(({ref:e,children:t,value:n,inputId:l,className:u,focused:d,isLoading:m,placeholder:h,disabled:b,canClose:f,onChange:p,onReset:g,onFocus:O,onBlur:v})=>{let j=Object(a.q)(null);e&&(j=e);const[E,y,N]=Object(c.a)(d);Object(a.n)(()=>{j.current&&(d?j.current.focus():j.current.blur())},[d,h]);const T=Object(s.a)();return a.a.createElement("div",{className:Object(r.a)("SearchInput",u,E&&"has-focus")},t,a.a.createElement("input",{ref:j,id:l,type:"text",placeholder:h||T("Search"),className:"form-control",value:n,disabled:b,onChange:function(e){const{currentTarget:t}=e;p(t.value)},onFocus:function(){y(),O&&O()},onBlur:function(){N(),v&&v()}}),a.a.createElement("i",{className:"icon-search"}),m&&a.a.createElement(i.a,null),!m&&(n||f)&&g&&a.a.createElement(o.a,{round:!0,size:"tiny",color:"translucent",onClick:g},a.a.createElement("span",{className:"icon-close"})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(9),r=n(55),c=n(7);function s(e,t){c.d?Object(a.b)(()=>{!function(e,t){const{scrollLeft:n,offsetWidth:a,scrollWidth:c}=e;let s=t-n;if(s<0){const e=-n;s=Math.max(s,e)}else if(s>0){const e=c-(n+a);s=Math.min(s,e)}const i=e.scrollLeft+s,o=Date.now();Object(r.a)(()=>{const t=Math.min((Date.now()-o)/450,1),n=s*(1-function(e){return 1-(1-e)**3.5}(t));return e.scrollLeft=Math.round(i-n),t<1})}(e,t)}):e.scrollTo({left:t,behavior:"smooth"})}},function(e,t,n){"use strict";var a=n(7);t.a=(e,t)=>{a.d&&(e.style.overflow="hidden"),void 0!==t&&(e.scrollTop=t),a.d&&(e.style.overflow="")}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));function a(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(37);n(193);t.a=Object(a.h)(Object(r.h)((e,{typingStatus:t})=>{if(!t.userId)return{};return{typingUser:Object(c.Db)(e,t.userId)}})(({typingStatus:e,typingUser:t})=>{const n=t&&!t.isSelf&&Object(s.X)(t);return a.a.createElement("p",{className:"typing-status"},n&&a.a.createElement("span",{className:"sender-name"},Object(i.a)(n)),e.action,a.a.createElement("span",{className:"ellipsis"}))}))},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(3),o=n(94),l=n(101),u=n(99),d=n(25);n(196);t.a=Object(a.h)(Object(r.h)((e,{chat:t})=>{const n=Object(s.kb)(t.id),a=Object(c.O)(e,t.id),r=n&&!a,i=t&&Object(s.kb)(t.id)?Object(s.X)(Object(c.Db)(e,Object(s.T)(t))):void 0;return{isPrivateChat:n,isChatWithSelf:a,isChannel:Object(s.ib)(t),isBasicGroup:Object(s.hb)(t),isSuperGroup:Object(s.mb)(t),canDeleteForAll:r,chatTitle:Object(s.l)(t),contactName:i}},(e,t)=>Object(i.l)(t,["leaveChannel","deleteHistory","deleteChannel"]))(({isOpen:e,chat:t,isChannel:n,isPrivateChat:r,isChatWithSelf:c,isBasicGroup:s,isSuperGroup:i,canDeleteForAll:m,chatTitle:h,contactName:b,onClose:f,leaveChannel:p,deleteHistory:g,deleteChannel:O})=>{const v=Object(a.m)(()=>{g({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!0}),f()},[g,t.id,t.lastMessage,f]),j=Object(a.m)(()=>{r||s?g({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!1}):!n&&!i||t.isCreator?(n||i)&&t.isCreator&&O({chatId:t.id}):p({chatId:t.id}),f()},[r,s,n,i,t.isCreator,t.lastMessage,t.id,f,g,p,O]),E=Object(o.a)();return a.a.createElement(u.a,{isOpen:e,onClose:f,className:"DeleteChatModal",header:a.a.createElement("div",{className:"modal-header"},a.a.createElement(l.a,{size:"tiny",chat:t,isSavedMessages:c}),a.a.createElement("h3",{className:"modal-title"},n&&!t.isCreator?"Leave Channel?":n&&t.isCreator?"Delete and Leave Channel?":s||i?"Leave Group?":"Delete Chat?"))},n&&!t.isCreator?a.a.createElement("p",null,"Are you sure you want to leave channel ",a.a.createElement("strong",null,h),"?"):n&&t.isCreator?a.a.createElement("p",null,"Are you sure you want to delete and leave channel ",a.a.createElement("strong",null,h),"?"):s||i?a.a.createElement("p",null,"Are you sure you want to leave group ",a.a.createElement("strong",null,h),"?"):a.a.createElement("p",null,"Are you sure you want to delete chat with ",a.a.createElement("strong",null,b),"?"),m&&a.a.createElement(d.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:v},"Delete for ",b?"me and "+b:"Everyone"),a.a.createElement(d.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:j},n&&!t.isCreator?"Leave Channel":n&&t.isCreator?"Delete and Leave Channel":s||i?"Leave Group":"Delete"+(m?" just for me":"")),a.a.createElement(d.a,{className:"confirm-dialog-button",isText:!0,onClick:f},E("Cancel")))}))},function(e,t,n){"use strict";function a(e){e.dataset.patchedForSafari||(e.addEventListener("play",()=>{const t=e.currentTime;e.addEventListener("progress",(function n(){e.buffered.length&&(e.dataset.patchForSafariInProgress="true",e.currentTime=e.duration-1,e.addEventListener("progress",()=>{delete e.dataset.patchForSafariInProgress,e.currentTime=t,e.paused&&e.play()},{once:!0}),e.removeEventListener("progress",n))}))},{once:!0}),e.dataset.patchedForSafari="true")}function r(e){return Boolean(e.dataset.patchForSafariInProgress)}n.d(t,"b",(function(){return a})),n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";var a=n(0),r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);return Object(a.o)(()=>{e(n||[])},t)}},function(e,t,n){"use strict";var a=n(0),r=n(53),c=n(5),s=n(96),i=n(111),o=n(97),l=n(167),u=n(168);t.a=Object(a.h)(({message:e,observeIntersection:t,smaller:n,uploadProgress:d,withDate:m,datetime:h,className:b,sender:f,isSelected:p,isSelectable:g,onCancelUpload:O,onDateClick:v})=>{const j=Object(a.q)(null),E=e.content.document,y=Object(r.b)(E)||"",{fileName:N,size:T,timestamp:C}=E,M=Object(s.b)(j,t),[w,I]=Object(a.r)(!1),{mediaData:S,downloadProgress:L}=Object(i.a)(Object(c.D)(e,"download"),!w),{isUploading:k,isTransferring:A,transferProgress:x}=Object(c.s)(e,d||L,w),D=Object(r.c)(E),_=D?Object(c.E)(e):void 0,R=D?E.previewBlobUrl:void 0,P=Object(o.a)(Object(c.D)(e,"pictogram"),!M),F=Object(a.m)(()=>{k?O&&O():I(e=>!e)},[k,O]),U=Object(a.m)(()=>{v(e.id,e.chatId)},[v,e.id,e.chatId]);return Object(a.n)(()=>{w&&S&&(Object(l.a)(S,N),I(!1))},[N,S,w]),a.a.createElement(u.a,{ref:j,name:N,extension:y,size:T,timestamp:m?h||C:void 0,thumbnailDataUri:_,previewData:R||P,smaller:n,isTransferring:A,isUploading:k,transferProgress:x,className:b,sender:f,isSelectable:g,isSelected:p,onClick:F,onDateClick:v?U:void 0})})},function(e,t,n){"use strict";var a=n(0),r=n(12),c=n(17);t.a=e=>{const{isOpen:t}=e,n=Object(c.a)(r.a.Extra,"StickerSetModal",!t);return n?a.a.createElement(n,e):void 0}},function(e,t,n){"use strict";var a=n(0),r=n(1),c=n(8),s=n(42),i=n(29),o=n(69),l=n(28),u=n(94),d=n(25);n(228);const m={B:"bold",STRONG:"bold",I:"italic",EM:"italic",U:"underline",DEL:"strikethrough",CODE:"monospace"};t.a=Object(a.h)(({isOpen:e,anchorPosition:t,selectedRange:n,onClose:h})=>{const b=Object(a.q)(null),f=Object(a.q)(null),{shouldRender:p,transitionClassNames:g}=Object(i.a)(e),[O,v,j]=Object(l.a)(),[E,y]=Object(a.r)(""),[N,T]=Object(a.r)(!1),[C,M]=Object(a.r)(),[w,I]=Object(a.r)({});Object(a.n)(()=>e?Object(s.a)(h):void 0,[e,h]),Object(o.a)(e,b,h),Object(a.n)(()=>{O?f.current.focus():(y(""),T(!1))},[O]),Object(a.n)(()=>{p||(j(),I({}),M(void 0))},[j,p]),Object(a.n)(()=>{if(!e||!n)return;const t={};let{parentElement:a}=n.commonAncestorContainer;for(;a&&a.id!==r.u;){const e=m[a.tagName];e&&(t[e]=!0),a=a.parentElement}I(t)},[e,n,v]);const S=Object(a.m)(()=>{if(n)return n.toString()},[n]),L=Object(a.m)(()=>{if(n)return n.commonAncestorContainer.parentElement},[n]);function k(){const e=f.current;if(!e)return;const{offsetWidth:t,scrollWidth:n,scrollLeft:a}=e;if(n<=t)return void M(void 0);let r="";a0&&(r+=" mask-left"),M(r)}function A(e){if(w[e])return"active";if("monospace"===e||"strikethrough"===e){if(Object.keys(w).some(t=>t!==e&&!!w[t]))return"disabled"}else if(w.monospace||w.strikethrough)return"disabled"}const x=Object(a.m)(()=>{I(e=>(document.execCommand(e.bold?"removeFormat":"bold"),Object.keys(e).forEach(t=>{"italic"!==t&&"underline"!==t||!e[t]||document.execCommand(t)}),{...e,bold:!e.bold}))},[]),D=Object(a.m)(()=>{document.execCommand("italic"),I(e=>({...e,italic:!e.italic}))},[]),_=Object(a.m)(()=>{document.execCommand("underline"),I(e=>({...e,underline:!e.underline}))},[]),R=Object(a.m)(()=>{if(w.strikethrough){const e=L();if(!n||!e||"DEL"!==e.tagName||!e.textContent)return;return e.replaceWith(e.textContent),void I(e=>({...e,strikethrough:!1}))}const e=S();document.execCommand("insertHTML",!1,`${e}`),h()},[L,S,h,n,w.strikethrough]),P=Object(a.m)(()=>{if(w.monospace){const e=L();if(!n||!e||"CODE"!==e.tagName||!e.textContent)return;return e.replaceWith(e.textContent),void I(e=>({...e,monospace:!1}))}const e=S();document.execCommand("insertHTML",!1,`${e}`),h()},[L,S,h,n,w.monospace]);function F(){const e=E.includes("://")?E:"http://"+E;if(N){const t=L();if(!t||"A"!==t.tagName)return;return t.href=e,void h()}const t=S();!function(){if(!n)return;const e=window.getSelection();e&&(e.removeAllRanges(),e.addRange(n))}(),document.execCommand("insertHTML",!1,`${t}`),h()}const U=Object(a.m)(e=>{const t={KeyK:v,KeyB:x,KeyU:_,KeyI:D,KeyM:P,KeyS:R}[e.code];!e.altKey&&(e.ctrlKey||e.metaKey)&&t&&(e.preventDefault(),e.stopPropagation(),t())},[x,D,_,P,R,v]);Object(a.n)(()=>(e&&document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)),[e,U]);const B=Object(u.a)();if(!p)return;const q=Object(c.a)("TextFormatter",g,O&&"link-control-shown"),H=Object(c.a)("TextFormatter-link-url-confirm",!!E.length&&"shown"),$=t?`left: ${t.x}px; top: ${t.y}px;--text-formatter-left: ${t.x}px;`:"";return a.a.createElement("div",{ref:b,className:q,style:$,onKeyDown:function(e){"Enter"===e.key&&O&&(F(),e.preventDefault())}},a.a.createElement("div",{className:"TextFormatter-buttons"},a.a.createElement(d.a,{color:"translucent",ariaLabel:"Bold text",className:A("bold"),onClick:x},a.a.createElement("i",{className:"icon-bold"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Italic text",className:A("italic"),onClick:D},a.a.createElement("i",{className:"icon-italic"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Underlined text",className:A("underline"),onClick:_},a.a.createElement("i",{className:"icon-underlined"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Strikethrough text",className:A("strikethrough"),onClick:R},a.a.createElement("i",{className:"icon-strikethrough"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Monospace text",className:A("monospace"),onClick:P},a.a.createElement("i",{className:"icon-monospace"})),a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement(d.a,{color:"translucent",ariaLabel:B("TextFormat.AddLinkTitle"),onClick:v},a.a.createElement("i",{className:"icon-link"}))),a.a.createElement("div",{className:"TextFormatter-link-control"},a.a.createElement("div",{className:"TextFormatter-buttons"},a.a.createElement(d.a,{color:"translucent",ariaLabel:B("Cancel"),onClick:j},a.a.createElement("i",{className:"icon-arrow-left"})),a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement("div",{className:Object(c.a)("TextFormatter-link-url-input-wrapper",C)},a.a.createElement("input",{ref:f,className:"TextFormatter-link-url-input",type:"text",value:E,placeholder:"Enter URL...",autoComplete:"off",inputMode:"url",onChange:function(e){y(e.target.value),k()},onScroll:k})),a.a.createElement("div",{className:H},a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement(d.a,{color:"translucent",ariaLabel:B("Save"),className:"color-primary",onClick:F},a.a.createElement("i",{className:"icon-check"}))))))})},function(e,t,n){"use strict";var a=n(0),r=n(30),c=n(5),s=n(97),i=n(104);n(236);t.a=Object(a.h)(({message:e,idPrefix:t="shared-media",onClick:n})=>{const o=Object(a.m)(()=>{n(e.id,e.chatId)},[e.id,e.chatId,n]),l=Object(c.E)(e),u=Object(s.a)(Object(c.D)(e,"pictogram")),{shouldRenderThumb:d,shouldRenderFullMedia:m,transitionClassNames:h}=Object(i.a)(u,"slow"),b=Object(c.O)(e);return a.a.createElement("div",{id:`${t}${e.id}`,className:"Media scroll-item",onClick:n?o:void 0},d&&a.a.createElement("img",{src:l,alt:""}),m&&a.a.createElement("img",{src:u,className:h+" full-media",alt:""}),b&&a.a.createElement("span",{className:"video-duration"},b.isGif?"GIF":Object(r.e)(b.duration)))})},,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(7),s=n(30),i=n(5);var o=n(8),l=n(37);var u=n(111),d=n(29),m=n(123),h=n(165),b=n(94),f=n(25),p=n(112),g=n(110);n(210);const O=c.f?20:25,v=c.f?50:75;function j(e,t,{handleStartSeek:n,handleSeek:r,handleStopSeek:c}){return a.a.createElement("div",{className:"seekline no-selection",onMouseDown:n,onMouseMove:r,onMouseUp:c},a.a.createElement("span",{className:"seekline-buffered-progress"},a.a.createElement("i",{style:`transform: translateX(${100*t}%)`})),a.a.createElement("span",{className:"seekline-play-progress"},a.a.createElement("i",{style:`transform: translateX(${100*e}%)`})),a.a.createElement("span",{className:"seekline-thumb"},a.a.createElement("i",{style:`transform: translateX(${100*e}%)`})))}t.a=Object(a.h)(Object(r.h)(e=>({theme:e.settings.byKey.theme}))(({theme:e,message:t,senderTitle:n,uploadProgress:r,renderingFor:E,date:y,lastSyncTime:N,className:T,isSelectable:C,isSelected:M,onPlay:w,onReadMedia:I,onCancelUpload:S,onDateClick:L})=>{const{content:{audio:k,voice:A},isMediaUnread:x}=t,D=Boolean(A),_=Object(a.q)(!1),[R,P]=Object(a.r)(!1),F=N,{mediaData:U,downloadProgress:B}=Object(u.a)(Object(i.D)(t,"inline"),!F,Object(i.C)(t,"inline"));const{isBuffered:q,bufferedProgress:H,bufferingHandlers:$,checkBuffering:Y}=Object(m.a)(),{isPlaying:V,playProgress:K,playPause:z,setCurrentTime:W,duration:X}=Object(h.a)(Object(i.A)(t),Object(i.r)(t),U,$,Y,R,(function(){P(!0),w(t.id,t.chatId)}),Object(i.rb)(t));Object(a.n)(()=>{P(V)},[V]);const{isUploading:G,isTransferring:Q,transferProgress:J}=Object(i.s)(t,r||B,R&&!q),{shouldRender:Z,transitionClassNames:ee}=Object(d.a)(Q),te=Object(a.m)(()=>{G?S&&S():(V||w(t.id,t.chatId),P(!R),z())},[V,G,t.id,t.chatId,S,w,z,R]);Object(a.n)(()=>{V&&I&&x&&I()},[V,x,I]);const ne=Object(a.m)(e=>{if(_.current){const t=e.currentTarget.closest(".seekline,.waveform");if(t){const{width:n,left:a}=t.getBoundingClientRect();W(X*((e.clientX-a)/n))}}},[X,W]),ae=Object(a.m)(e=>{_.current=!0,ne(e)},[ne]),re=Object(a.m)(()=>{_.current=!1},[]),ce=Object(a.m)(()=>{L(t.id,t.chatId)},[L,t.id,t.chatId]);Object(b.a)();const se={handleStartSeek:ae,handleSeek:ne,handleStopSeek:re},ie=Object(i.sb)(t),oe=Object(a.p)(()=>A&&function(e,t=0,n=!1,{handleStartSeek:r,handleSeek:c,handleStopSeek:s},i){const{waveform:o,duration:l}=e;if(!o)return;const u="dark"===i?"#494B75":"#CBCBCB",d="dark"===i?"#C69C85":"#B0DEA6",m="dark"===i?"#868DF5":"#54a3e6",h="dark"===i?"#FFFFFF":"#53ad53",b=Math.min(l/30,1),f=Math.round(O+(v-O)*b),p=function(e){const t=8*e.length,n=Math.floor(t/5);if(!n)return[];const a=Array(n),r=e;for(let e=0,t=n-1;e!==t;++e){const t=Math.floor(5*e/8),n=Math.floor(5*e%8),c=r[t]+(r[t+1]<<8);a[e]=c>>n&31}const c=Math.floor(5*(n-1)/8),s=Math.floor(5*(n-1)%8),i=r[c]+(r[c+1]<<8);return a[n-1]=i>>s&31,a}(new Uint8Array(o)),{data:g,peak:j}=function(e,t){let n=0;const a=new Array(t),r=e.length/t,c=e[0],s=e[e.length-1];for(let u=0;u{i.globalAlpha=s/e.length>=t?.5:1,i.fillStyle=t>s/e.length?r:a;const o=Math.max(2,c/Math.max(1,n)*23);!function(e,t,n,a,r,c){a<2*c&&(c=a/2);r<2*c&&(c=r/2);e.beginPath(),e.moveTo(t+c,n),e.arcTo(t+a,n,t+a,n-r,c),e.arcTo(t+a,n-r,t,n-r,c),e.arcTo(t,n-r,t,n,c),e.arcTo(t,n,t+a,n,c),e.closePath()}(i,4*s,23,2,o,1),i.fill()}),{src:s.toDataURL(),width:c,height:23}}(g,t,{peak:j,fillStyle:n?d:u,progressFillStyle:n?h:m});return a.a.createElement("img",{src:E,alt:"",width:y,height:N,className:"waveform",draggable:!1,onMouseDown:r,onMouseMove:c,onMouseUp:s})}(A,K,ie,se,e),[A,K,ie,se,e]),le=Object(o.a)("Audio media-inner",T,ie&&!E&&"own",E&&"bigger",M&&"audio-is-selected"),ue=["toggle-play"];Z?ue.push("loading"):V?ue.push("pause"):V||ue.push("play");const de=V||K>0&&K<1,me=Object(o.a)("content",de&&"with-seekline");return a.a.createElement("div",{className:le},C&&a.a.createElement("div",{className:"message-select-control"},M&&a.a.createElement("i",{className:"icon-select"})),a.a.createElement(f.a,{round:!0,ripple:!c.f,size:E?"smaller":"tiny",className:ue.join(" "),ariaLabel:V?"Pause audio":"Play audio",onClick:te},a.a.createElement("i",{className:"icon-play"}),a.a.createElement("i",{className:"icon-pause"})),Z&&a.a.createElement("div",{className:Object(o.a)("media-loading",ee)},a.a.createElement(p.a,{progress:J,transparent:!0,size:E?"m":"s",onClick:te})),"searchResult"===E&&a.a.createElement(a.a.Fragment,null,a.a.createElement("div",{className:me},a.a.createElement("div",{className:"content-row"},a.a.createElement("p",{className:"title"},Object(l.a)(function(){if(D)return n||"Voice";const{title:e,fileName:t}=k;return e||t}())),a.a.createElement("div",{className:"message-date"},y&&a.a.createElement(g.a,{className:"date",onClick:ce},Object(s.g)(1e3*y)))),de&&j(K,H,se),!de&&a.a.createElement("p",{className:"duration"},K>0?Object(s.e)(X*K)+" / ":void 0,function(){if(D)return Object(s.e)(A.duration);const{performer:e}=k;return a.a.createElement(a.a.Fragment,null,e&&Object(l.a)(e),e&&n&&a.a.createElement("span",null,"•"),n&&Object(l.a)(n))}()))),"searchResult"!==E&&k&&function(e,t,n,r,c,i,o){const{title:u,performer:d,duration:m,fileName:h}=e,b=t||n>0&&n<1;return a.a.createElement("div",{className:"content"},a.a.createElement("p",{className:"title"},Object(l.a)(u||h)),b&&j(n,r,c),!b&&a.a.createElement("div",{className:"meta"},a.a.createElement("span",{className:"performer"},Object(l.a)(d||"Unknown")),i&&a.a.createElement(a.a.Fragment,null," ","•"," ",a.a.createElement(g.a,{className:"date",onClick:o},Object(s.d)(1e3*i)))),a.a.createElement("p",{className:"duration"},n>0?Object(s.e)(m*n)+" / ":void 0,Object(s.e)(m)))}(k,V,K,H,se,y,L?ce:void 0),"searchResult"!==E&&A&&function(e,t,n){return a.a.createElement("div",{className:"content"},t,a.a.createElement("p",{className:"voice-duration"},Object(s.e)(e.duration),n&&a.a.createElement("span",null,"•")))}(A,oe,x))}))},function(e,t,n){"use strict";var a=n(0),r=n(145),c=n(38),s=n(130),i=n(94),o=n(8);n(189);var l=Object(a.h)(({className:e,title:t,active:n,badgeCount:r,isBadgeActive:c,previousActiveTab:s,onClick:i,clickArg:l})=>{const u=Object(a.q)(null);return Object(a.o)(()=>{if(!n||void 0===s)return;const e=u.current,t=e.querySelector("i"),a=e.parentElement.children[s].querySelector("i");a.classList.remove("animate"),t.classList.remove("animate");const r=a.parentElement.offsetLeft-t.parentElement.offsetLeft,c=a.clientWidth/t.clientWidth;t.style.transform=`translate3d(${r}px, 0, 0) scale3d(${c}, 1, 1)`,requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{t.classList.add("animate"),t.style.transform="none"})})})},[n,s]),a.a.createElement("button",{type:"button",className:Object(o.a)("Tab",e,n&&"active"),onClick:()=>i(l),ref:u},a.a.createElement("span",null,t,!!r&&a.a.createElement("span",{className:Object(o.a)("badge",c&&"active")},r),a.a.createElement("i",null)))});n(190);t.a=Object(a.h)(({tabs:e,activeTab:t,onSwitchTab:n})=>{const o=Object(a.q)(null),u=Object(c.a)(t);Object(s.a)(o),Object(a.n)(()=>{const e=o.current;if(e.scrollWidth<=e.offsetWidth)return;const t=e.querySelector(".Tab.active");if(t){const n=t.offsetLeft-e.offsetWidth/2+t.offsetWidth/2;if(Math.abs(n-e.scrollLeft)<16)return;Object(r.a)(e,n)}},[t]);const d=Object(i.a)();return a.a.createElement("div",{className:"TabList no-selection no-scrollbar",ref:o},e.map((e,r)=>a.a.createElement(l,{key:e.title,title:d(e.title),active:r===t,badgeCount:e.badgeCount,isBadgeActive:e.isBadgeActive,previousActiveTab:u,onClick:n,clickArg:r})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const a={CHAT_RESTRICTED:"You can't send messages in this chat, you were restricted",CHAT_WRITE_FORBIDDEN:"You can't write in this chat",CHAT_SEND_POLL_FORBIDDEN:"You can't create polls in this chat",CHAT_SEND_STICKERS_FORBIDDEN:"You can't send stickers in this chat",CHAT_SEND_GIFS_FORBIDDEN:"You can't send gifs in this chat",CHAT_SEND_MEDIA_FORBIDDEN:"You can't send media in this chat",CHAT_LINK_EXISTS:"The chat is public, you can't hide the history to new users",SLOWMODE_WAIT_X:"Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.",USER_BANNED_IN_CHANNEL:"You're banned from sending messages in supergroups / channels",USER_IS_BLOCKED:"You were blocked by this user",YOU_BLOCKED_USER:"You blocked this user",IMAGE_PROCESS_FAILED:"Failure while processing image",MEDIA_EMPTY:"The provided media object is invalid",MEDIA_INVALID:"Media invalid",PHOTO_EXT_INVALID:"The extension of the photo is invalid",PHOTO_INVALID_DIMENSIONS:"The photo dimensions are invalid",PHOTO_SAVE_FILE_INVALID:"Internal issues, try again later",MESSAGE_DELETE_FORBIDDEN:"You can't delete one of the messages you tried to delete, most likely because it is a service message.",MESSAGE_POLL_CLOSED:"Poll closed",MESSAGE_EDIT_TIME_EXPIRED:"You can't edit this message anymore.",CHAT_ADMIN_REQUIRED:"You must be an admin in this chat to do this",PINNED_DIALOGS_TOO_MUCH:"Sorry, you can only pin 5 chats to the top",DIALOG_FILTERS_TOO_MUCH:"Sorry, you can't have more than 10 folders",CHANNEL_PRIVATE:"This channel is private",MEDIA_CAPTION_TOO_LONG:"The provided caption is too long",ADDRESS_STREET_LINE1_INVALID:"The address you provided is not valid",ADDRESS_STREET_LINE2_INVALID:"The address you provided is not valid",ADDRESS_CITY_INVALID:"The city you provided is not valid",ADDRESS_COUNTRY_INVALID:"The country you provided is not valid",ADDRESS_POSTCODE_INVALID:"The postcode you provided is not valid",ADDRESS_STATE_INVALID:"The state you provided is not valid",REQ_INFO_NAME_INVALID:"The name you provided is not valid",REQ_INFO_PHONE_INVALID:"The phone you provided is not valid",REQ_INFO_EMAIL_INVALID:"The email you provided is not valid",LINK_NOT_MODIFIED:"This discussion is already linked to the channel",SERVICE_WORKER_DISABLED:"Service Worker is disabled. Please reload the page without holding key.",CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS:"The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.",FRESH_RESET_AUTHORISATION_FORBIDDEN:"You can’t logout other sessions if less than 24 hours have passed since you logged on the current session",BOTS_TOO_MUCH:"There are too many bots in this chat/channel",BOT_GROUPS_BLOCKED:"This bot can't be added to groups",USERS_TOO_MUCH:"The maximum number of users has been exceeded",USER_CHANNELS_TOO_MUCH:"One of the users you tried to add is already in too many channels/supergroups",USER_KICKED:"This user was kicked from this supergroup/channel",USER_NOT_MUTUAL_CONTACT:"The provided user is not a mutual contact",USER_PRIVACY_RESTRICTED:"The user's privacy settings do not allow you to do this",INVITE_HASH_EMPTY:"The invite hash is empty",INVITE_HASH_EXPIRED:"The invite link has expired",INVITE_HASH_INVALID:"The invite hash is invalid",CHANNELS_TOO_MUCH:"You have joined too many channels/supergroups",USER_ALREADY_PARTICIPANT:"You already in the group"};function r(e){const{message:t,isSlowMode:n,textParams:r}=e;if(n){const e=t.indexOf(" (caused by");return e>0?t.substring(0,e):t}let c=a[t];return c&&r&&(c=Object.keys(r).reduce((e,t)=>e.replace(t,r[t]),c)),c}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(5);t.a=({chat:e,privateChatUser:t,handleDelete:n,folderId:s,isPinned:i})=>{const{toggleChatPinned:o,updateChatMutedState:l,toggleChatArchived:u,toggleChatUnread:d}=Object(r.d)();return Object(a.p)(()=>{if(!e)return;const a=t&&t.isSelf,r=e.unreadCount||e.hasUnreadMark?{title:"Mark as Read",icon:"readchats",handler:()=>d({id:e.id})}:{title:"Mark as Unread",icon:"unread",handler:()=>d({id:e.id})},m=i?{title:"Unpin",icon:"unpin",handler:()=>o({id:e.id,folderId:s})}:{title:"Pin",icon:"pin",handler:()=>o({id:e.id,folderId:s})},h=e.isMuted?{title:"Unmute",icon:"unmute",handler:()=>l({chatId:e.id,isMuted:!1})}:{title:"Mute",icon:"mute",handler:()=>l({chatId:e.id,isMuted:!0})},b=Object(c.gb)(e)?{title:"Unarchive",icon:"unarchive",handler:()=>u({id:e.id})}:{title:"Archive",icon:"archive",handler:()=>u({id:e.id})};return[r,m,...a?[]:[h,b],{title:Object(c.kb)(e.id)?"Delete":Object(c.d)(e)?"Delete and Leave":"Leave",icon:"delete",destructive:!0,handler:n}]},[e,t,n,s,i,o,l,u,d])}},function(e,t,n){"use strict";var a=n(0),r=n(30),c=n(162);n(195);t.a=({message:e,outgoingStatus:t})=>a.a.createElement("div",{className:"LastMessageMeta"},t&&a.a.createElement(c.a,{status:t}),a.a.createElement("span",{className:"time"},Object(r.g)(1e3*e.date)))},function(e,t,n){"use strict";var a,r=n(0),c=n(100);n(194);!function(e){e[e.failed=0]="failed",e[e.pending=1]="pending",e[e.succeeded=2]="succeeded",e[e.read=3]="read"}(a||(a={}));t.a=({status:e})=>r.a.createElement("div",{className:"MessageOutgoingStatus"},r.a.createElement(c.a,{name:"reveal",activeKey:a[e]},()=>r.a.createElement("i",{className:"icon-message-"+e})))},function(e,t,n){"use strict";var a=n(0);t.a=(e,t,n,r,c=0,s=0)=>{const[i,o]=Object(a.r)("right"),[l,u]=Object(a.r)("bottom"),[d,m]=Object(a.r)("");return Object(a.n)(()=>{const a=t();if(!e||!a)return;let{x:i,y:l}=e;const d={width:0,left:0,height:0,top:0},h=r(),b=n(),f=a.getBoundingClientRect(),p=h?{width:h.offsetWidth,height:h.offsetHeight}:d,g=b?b.getBoundingClientRect():d;i+p.width+c0?(o("right"),i-=3):(o("left"),i=16),l+p.height{const{shouldRender:u,transitionClassNames:d}=Object(r.a)(e,void 0,void 0,!t&&void 0),m=Object(c.a)(e),h=Object(c.a)(l),b=Object(a.q)();return m&&!e&&(b.current=h),u&&a.a.createElement("div",{id:n,className:Object(s.a)(i,d),onClick:o},e?l():b.current())}},function(e,t,n){"use strict";var a=n(0),r=n(166),c=n(52),s=n(150),i=n(103);t.a=(e,t,n,o,l,u=!1,d,m=!1)=>{const h=Object(a.q)(null),[b,f]=Object(a.r)(!1);let p=b;const[g,O]=Object(a.r)(0);Object(i.a)(()=>{h.current=Object(r.a)(e,(e,n)=>{switch(e){case"onPlay":f(!0);break;case"onPause":f(!1);break;case"onTimeUpdate":{const{proxy:e}=h.current,n=e.duration&&Number.isFinite(e.duration)?e.duration:t;O(e.currentTime/n);break}}o&&o[e]&&o[e](n)},d);const{proxy:n}=h.current;b||n.paused||(f(!0),p=!0),l&&l(n)},[e]);const{play:v,pause:j,setCurrentTime:E,proxy:y,destroy:N}=h.current,T=y.duration&&Number.isFinite(y.duration)?y.duration:t;Object(a.n)(()=>{T&&!Object(s.a)(y)&&O(y.currentTime/T)},[T,g,y]),Object(a.n)(()=>()=>{N(m)},[N,m]),Object(c.a)(([e,t])=>{e===u&&n===t||y.src&&y.paused||u&&n&&!b&&v(n)},[u,n,b,v,y.src,y.paused]);const C=Object(a.m)(()=>{b?j():n&&v(n)},[n,j,v,b]);return{isPlaying:p,playProgress:g,playPause:C,setCurrentTime:E,audioProxy:y,duration:T}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return m}));var a=n(7),r=n(134),c=n(150),s=n(2),i=n(5);const o=new Map;let l,u=[];function d(){const e=l&&o.get(l);e&&e.audio.pause()}function m(e,t,n){o.has(e)||(o.set(e,function(e,t){const n=new Audio;function a(t){return a=>{o.has(e)&&(Object(c.a)(n)||o.get(e).handlers.forEach(e=>{e(t,a)}))}}return n.addEventListener("timeupdate",a("onTimeUpdate")),n.addEventListener("play",a("onPlay")),n.addEventListener("pause",a("onPause")),n.addEventListener("loadstart",a("onLoadStart")),n.addEventListener("loadeddata",a("onLoadedData")),n.addEventListener("playing",a("onPlaying")),n.addEventListener("ended",()=>{if(Object(c.a)(n))return;const t=u[u.indexOf(e)+1];if(!t)return;if(!o.has(t))return void Object(s.d)().openAudioPlayer(Object(i.yb)(t));const a=o.get(t);a.onForcePlay&&a.onForcePlay(),l=t,a.audio.src&&Object(r.a)(a.audio)}),{audio:n,proxy:new Proxy(n,{get:(e,t)=>e[t]}),handlers:[],onForcePlay:t}}(e,n)),u.includes(e)||u.push(e));const{audio:d,proxy:m,handlers:h}=o.get(e);return h.push(t),{play(t){l&&l!==e&&o.get(l).audio.pause(),l=e,d.src||(d.src=t,d.preload="auto",t.includes("/progressive/")&&a.i&&Object(c.b)(d)),Object(r.a)(d)},pause(){l===e&&d.pause()},setCurrentTime(t){l===e&&(d.currentTime=t)},proxy:m,destroy(n=!1){const a=o.get(e);a&&(a.handlers=a.handlers.filter(e=>e!==t),a.handlers.length||(a.audio.pause(),o.delete(e),n&&(u=u.filter(t=>t!==e)),e===l&&(l=void 0)))}}}},function(e,t,n){"use strict";function a(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.click()}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a=n(0),r=n(29),c=n(104),s=n(8),i=n(30),o=n(53),l=n(105),u=n(37),d=n(112),m=n(110);n(209);t.a=Object(a.h)(({ref:e,name:t,size:n,extension:h="",timestamp:b,sender:f,thumbnailDataUri:p,previewData:g,className:O,smaller:v,isTransferring:j,isUploading:E,isSelectable:y,isSelected:N,transferProgress:T,onClick:C,onDateClick:M})=>{let w=Object(a.q)(null);e&&(w=e);const{shouldRender:I,transitionClassNames:S}=Object(r.a)(j,void 0,!0),L=Object(o.a)(h),k=Object(o.e)(n),{shouldRenderThumb:A,shouldRenderFullMedia:x,transitionClassNames:D}=Object(c.a)(g,"slow"),{width:_,height:R}=Object(l.i)(v),P=Object(s.a)("File",O,v&&"smaller",C&&!E&&"interactive",N&&"file-is-selected");return a.a.createElement("div",{ref:w,className:P},y&&a.a.createElement("div",{className:"message-select-control"},N&&a.a.createElement("i",{className:"icon-select"})),a.a.createElement("div",{className:"file-icon-container",onClick:E?void 0:C},p||g?a.a.createElement("div",{className:"file-preview media-inner"},A&&a.a.createElement("img",{src:p,width:_,height:R,className:"thumbnail",alt:""}),x&&a.a.createElement("img",{src:g,className:"full-media "+D,width:_,height:R,alt:""})):a.a.createElement("div",{className:"file-icon "+L},h.length<=4&&a.a.createElement("span",{className:"file-ext"},h)),I&&a.a.createElement("div",{className:Object(s.a)("file-progress",L,S)},a.a.createElement(d.a,{progress:T,size:v?"s":"m",onClick:E?C:void 0})),C&&a.a.createElement("i",{className:Object(s.a)("icon-download",I&&"hidden")})),a.a.createElement("div",{className:"file-info"},a.a.createElement("div",{className:"file-title"},Object(u.a)(t)),a.a.createElement("div",{className:"file-subtitle"},a.a.createElement("span",null,j&&T?Math.round(100*T)+"%":k),f&&a.a.createElement("span",{className:"file-sender"},Object(u.a)(f)),!f&&b&&a.a.createElement(a.a.Fragment,null," ",a.a.createElement(m.a,{onClick:M},Object(i.d)(1e3*b))))),f&&b&&a.a.createElement(m.a,{onClick:M},Object(i.g)(1e3*b)))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));const a=[1,57,41,21,203,34,97,73,227,91,149,62,105,45,39,137,241,107,3,173,39,71,65,238,219,101,187,87,81,151,141,133,249,117,221,209,197,187,177,169,5,153,73,139,133,127,243,233,223,107,103,99,191,23,177,171,165,159,77,149,9,139,135,131,253,245,119,231,224,109,211,103,25,195,189,23,45,175,171,83,81,79,155,151,147,9,141,137,67,131,129,251,123,30,235,115,113,221,217,53,13,51,50,49,193,189,185,91,179,175,43,169,83,163,5,79,155,19,75,147,145,143,35,69,17,67,33,65,255,251,247,243,239,59,29,229,113,111,219,27,213,105,207,51,201,199,49,193,191,47,93,183,181,179,11,87,43,85,167,165,163,161,159,157,155,77,19,75,37,73,145,143,141,35,138,137,135,67,33,131,129,255,63,250,247,61,121,239,237,117,29,229,227,225,111,55,109,216,213,211,209,207,205,203,201,199,197,195,193,48,190,47,93,185,183,181,179,178,176,175,173,171,85,21,167,165,41,163,161,5,79,157,78,154,153,19,75,149,74,147,73,144,143,71,141,140,139,137,17,135,134,133,66,131,65,129,1],r=[0,9,10,10,14,12,14,14,16,15,16,15,16,15,15,17,18,17,12,18,16,17,17,19,19,18,19,18,18,19,19,19,20,19,20,20,20,20,20,20,15,20,19,20,20,20,21,21,21,20,20,20,21,18,21,21,21,21,20,21,17,21,21,21,22,22,21,22,22,21,22,21,19,22,22,19,20,22,22,21,21,21,22,22,22,18,22,22,21,22,22,23,22,20,23,22,22,23,23,21,19,21,21,21,23,23,23,22,23,23,21,23,22,23,18,22,23,20,22,23,23,23,21,22,20,22,21,22,24,24,24,24,24,22,21,24,23,23,24,21,24,23,24,22,24,24,22,24,24,22,23,24,24,24,20,23,22,23,24,24,24,24,24,24,24,23,21,23,22,23,24,24,24,22,24,24,24,23,22,24,24,25,23,25,25,23,24,25,25,24,22,25,25,25,24,23,24,25,25,25,25,25,25,25,25,25,25,25,25,23,25,23,24,25,25,25,25,25,25,25,25,25,24,22,25,25,23,25,25,20,24,25,24,25,25,22,24,25,24,25,24,25,25,24,25,25,25,25,22,25,25,25,24,25,24,25,18];function c(e,t,n,c,s,i,o){if(Number.isNaN(i)||i<1)return;i|=0,Number.isNaN(o)&&(o=1),(o|=0)>3&&(o=3),o<1&&(o=1);const l=e.getImageData(t,n,c,s),u=l.data;let d,m,h,b,f,p,g,O,v,j,E,y,N=c-1,T=s-1,C=i+1,M=[],w=[],I=[],S=a[i],L=r[i],k=[],A=[];for(;o-- >0;){for(y=E=0,f=0;fN?N:p)<<2),d+=u[g++],m+=u[g++],h+=u[g++];for(b=0;b0?g<<2:0),O=y+k[b],v=y+A[b],d+=u[O++]-u[v++],m+=u[O++]-u[v++],h+=u[O++]-u[v++],E++;y+=c<<2}for(b=0;bT?0:c,d+=M[j],m+=w[j],h+=I[j];for(E=b<<2,f=0;f>>L,u[E+1]=m*S>>>L,u[E+2]=h*S>>>L,0==b&&(k[f]=((g=f+C)0?g*c:0),O=b+k[f],v=b+A[f],d+=M[O]-M[v],m+=w[O]-w[v],h+=I[O]-I[v],E+=c<<2}}e.putImageData(l,t,n)}},function(e,t,n){"use strict";var a=n(0),r=n(1),c=n(29),s=n(8),i=n(42),o=n(113);n(216);t.a=Object(a.h)(({message:e,duration:t=3e3,onDismiss:n})=>{const[l,u]=Object(a.r)(!0),d=Object(a.q)(null),{transitionClassNames:m}=Object(c.a)(l),h=Object(a.m)(()=>{u(!1),setTimeout(n,150+r.c)},[n]);Object(a.n)(()=>l?Object(i.a)(h):void 0,[l,h]),Object(a.n)(()=>(d.current=window.setTimeout(h,t),()=>{d.current&&(clearTimeout(d.current),d.current=void 0)}),[t,h]);const b=Object(a.m)(()=>{d.current&&(clearTimeout(d.current),d.current=void 0)},[]),f=Object(a.m)(()=>{d.current=window.setTimeout(h,t)},[t,h]);return a.a.createElement(o.a,{className:"Notification-container",containerId:"#middle-column-portals"},a.a.createElement("div",{className:Object(s.a)("Notification",m),onClick:h,onMouseEnter:b,onMouseLeave:f},a.a.createElement("div",{className:"content"},e)))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var a=n(1);function r(e){const{commonAncestorContainer:t}=e;let n=t,r=1;for(;n&&n.id!==a.u&&r<5;)n=n.parentElement,r++;return Boolean(n&&n.id===a.u)}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(1),s=n(6),i=n(9),o=n(124),l=n(8),u=n(3),d=n(7),m=n(50),h=n(151),b=n(28),f=n(58),p=n(171),g=n(154);const O=d.f?256:416;t.a=Object(a.h)(Object(r.h)(e=>{const{chatId:t,threadId:n}=Object(s.y)(e)||{},{messageSendKeyCombo:a}=e.settings.byKey;return{currentChatId:t,messageSendKeyCombo:a,replyingToId:t&&n?Object(s.jb)(e,t,n):void 0,noTabCapture:e.isPollModalOpen||e.payment.isPaymentModalOpen}},(e,t)=>Object(u.l)(t,["editLastMessage"]))(({id:e,editableInputId:t,html:n,placeholder:r,shouldSetFocus:s,shouldSupressFocus:u,onUpdate:v,onSupressedFocus:j,onSend:E,currentChatId:y,replyingToId:N,noTabCapture:T,messageSendKeyCombo:C,editLastMessage:M})=>{const w=Object(a.q)(null),I=Object(a.q)(null),S=Object(a.q)(!1),[L,k,A]=Object(b.a)(),[x,D]=Object(a.r)(),[_,R]=Object(a.r)();Object(h.a)(([e])=>{n!==w.current.innerHTML&&(w.current.innerHTML=n),n!==I.current.innerHTML&&(I.current.innerHTML=n),void 0!==e&&e!==n&&function(e=!1){const t=w.current,n=I.current,a=Number(t.style.height.replace("px","")),r=Math.min(n.scrollHeight,O);if(r===a)return;const c=Math.round(50*Math.log(Math.abs(r-a))),s=()=>{t.style.height=r+"px",t.style.transitionDuration=c+"ms",t.classList.toggle("overflown",n.scrollHeight>O)};e?requestAnimationFrame(s):s()}(!n.length)},[n]);const P=Object(a.m)(()=>{w.current.closest(".from, .to")?setTimeout(P,350):Object(o.a)(w.current)},[]),F=Object(a.m)(()=>{A(),function(){const e=window.getSelection();e&&(e.removeAllRanges?e.removeAllRanges():e.empty&&e.empty())}()},[A]);function U(){if(d.d)return;const e=window.getSelection();if(!e||!e.rangeCount||S.current)return void A();const t=e.getRangeAt(0),n=t.toString().trim();if(!Object(p.a)(t)||!n||Object(f.a)(n)||!t.START_TO_END)return void A();const a=t.getBoundingClientRect(),r=w.current.getBoundingClientRect();let c=a.left+a.width/2-r.left;c<90?c=90:c>r.width-90&&(c=r.width-90),D({x:c,y:a.top-r.top}),R(t),k()}Object(a.n)(()=>{d.k||P()},[y,P,N,s]),Object(a.n)(()=>{if(T)return;const e=Object(i.a)(e=>{"Tab"===e.key&&(e.preventDefault(),requestAnimationFrame(P))},2e3,!0,!1);return Object(m.a)({onTab:e})},[P,T]),Object(a.n)(()=>{const e=w.current;function t(){e.blur()}return u&&e.addEventListener("focus",t),()=>{e.removeEventListener("focus",t)}},[u]);const B=Object(l.a)("form-control custom-scroll",n.length>0&&"touched",u&&"focus-disabled");return a.a.createElement("div",{id:e,onClick:u?j:void 0},a.a.createElement("div",{ref:w,id:t||c.u,className:B,contentEditable:!0,onClick:P,onChange:function(e){const{innerHTML:t,textContent:n}=e.currentTarget;if(v("
"===t?"":t),!(d.k||n&&n.length)){const e=window.getSelection();e&&(w.current.blur(),e.removeAllRanges(),Object(o.a)(w.current,!0))}},onKeyDown:function(e){"Enter"!==e.key||e.shiftKey?"ArrowUp"!==e.key||n.length?e.target.addEventListener("keyup",(function t(){U(),e.target.removeEventListener("keyup",t)})):(e.preventDefault(),M()):d.d||d.b||!("enter"===C&&!e.shiftKey||"ctrl-enter"===C&&(e.ctrlKey||e.metaKey))||(e.preventDefault(),A(),E())},onMouseDown:function(e){2===e.button?!0!==S.current&&(S.current=!0,document.addEventListener("mousedown",(function e(){setTimeout(()=>{S.current=!1},100),window.removeEventListener("mouseup",e)})),document.addEventListener("keydown",(function e(t){"Esc"!==t.key&&"Escape"!==t.key||(setTimeout(()=>{S.current=!1},100),window.removeEventListener("keydown",e))}))):e.target.addEventListener("mouseup",(function t(){U(),e.target.removeEventListener("mouseup",t)}))},onContextMenu:function(e){d.b&&(e.preventDefault(),e.stopPropagation())},onTouchCancel:function(){d.b&&U()}}),a.a.createElement("div",{ref:I,className:Object(l.a)(B,"clone")}),a.a.createElement("span",{className:"placeholder-text"},r),a.a.createElement(g.a,{isOpen:L,anchorPosition:x,selectedRange:_,onClose:F}))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var a=n(0),r=n(169),c=n(103),s=n(136),i=n(14);function o(e){const t=Object(a.q)();let n=!1;Object(c.a)(()=>{if(n=!0,t.current=void 0,!e)return;const a=new Image;if(a.src=e,!a.width)return;const c=Object(i.f)(a);Object(r.a)(c.getContext("2d"),0,0,c.width,c.height,2,2),t.current=c.toDataURL()},[e]);const o=Object(s.a)(e||void 0,Boolean(t.current));return t.current||!n&&o||e||void 0}},function(e,t,n){"use strict";var a=n(0),r=n(5),c=n(8),s=n(147),i=n(37),o=n(30),l=n(155),u=n(110),d=n(51);n(237);t.a=Object(a.h)(({message:e,senderTitle:t,onMessageClick:n})=>{let m=Object(r.P)(e);if(!m){const t=Object(r.n)(e);if(t){const{url:n,domain:a}=t,c=Object(r.M)(e);m={siteName:a.replace(/^www./,""),url:n.includes("://")?n:n.includes("@")?"mailto:"+n:"http://"+n,description:c!==n?c:void 0}}}const h=Object(a.m)(()=>{n(e.id,e.chatId)},[n,e.id,e.chatId]);if(!m)return;const{siteName:b,url:f,displayUrl:p,title:g,description:O,photo:v}=m,j=!t&&Object(s.a)(O,170),E=Object(c.a)("WebLink scroll-item",!v&&"without-photo");return a.a.createElement("div",{className:E,"data-initial":(b||p)[0]},v&&a.a.createElement(l.a,{message:e}),a.a.createElement("div",{className:"content"},a.a.createElement(u.a,{className:"site-title",onClick:h},Object(i.a)(g||b||p)),j&&a.a.createElement(u.a,{className:"site-description",onClick:h},Object(i.a)(j)),a.a.createElement(d.a,{url:f,className:"site-name",text:""},f.replace("mailto:","")||p),t&&a.a.createElement("div",{className:"sender-name"},Object(i.a)(t))),t&&a.a.createElement("div",{className:"message-date"},a.a.createElement(u.a,{className:"date",onClick:h},Object(o.g)(1e3*e.date))))})},,,,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(4),s=n(1),i=n(7),o=n(38),l=n(3),u=n(5),d=n(6),m=n(118);let h;!function(e){e[e.Move=0]="Move",e[e.Opacity=1]="Opacity",e[e.None=2]="None"}(h||(h={}));var b=n(102),f=n(16),p=n(94),g=n(179),O=n(37),v=n(9),j=n(8),E=n(131),y=n(160),N=n(28),T=n(97),C=n(101),M=n(122),w=n(148),I=n(161),S=n(149),L=n(95),k=n(44),A=n(164);n(198);var x=({chat:e,isPinned:t})=>{const n=Boolean(e.unreadCount||e.hasUnreadMark||t),r=Object(j.a)("Badge",e.isMuted&&"muted",t&&"pinned",Boolean(e.unreadCount||e.hasUnreadMark)&&"unread");function c(){return e.unreadCount?e.unreadMentionsCount?a.a.createElement("div",{className:"Badge-wrapper"},a.a.createElement("div",{className:"Badge mention"},a.a.createElement("i",{className:"icon-mention"})),a.a.createElement("div",{className:r},Object(k.b)(e.unreadCount))):a.a.createElement("div",{className:r},Object(k.b)(e.unreadCount)):e.hasUnreadMark?a.a.createElement("div",{className:r}):t?a.a.createElement("div",{className:r},a.a.createElement("i",{className:"icon-pinned-chat"})):void 0}return a.a.createElement(A.a,{isCustom:!0,className:"Badge-transition",isOpen:n},c)};n(199);var D,_=Object(a.h)(Object(r.h)((e,{chatId:t})=>{const n=Object(d.f)(e,t);if(!n||!n.lastMessage)return{};const{senderId:a,replyToMessageId:r,isOutgoing:s}=n.lastMessage,i=a?Object(d.Db)(e,a):void 0,o=Object(u.t)(n.lastMessage),l=o&&r?Object(d.k)(e,n.id,r):void 0,{targetUserId:m,targetChatId:h}=o||{},b=Object(u.T)(n),{type:f}=Object(d.y)(e)||{};return{chat:n,lastMessageSender:i,...s&&{lastMessageOutgoingStatus:Object(d.cb)(e,n.lastMessage)},...b&&{privateChatUser:Object(d.Db)(e,b)},...m&&{actionTargetUser:Object(d.Db)(e,m)},actionTargetChatId:h,actionTargetMessage:l,draft:Object(d.B)(e,t,c.MAIN_THREAD_ID),messageListType:f,animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(l.l)(t,["openChat","focusLastMessage"]))(({style:e,chatId:t,folderId:n,orderDiff:r,animationType:c,isSelected:o,isPinned:l,chat:d,privateChatUser:m,actionTargetUser:b,lastMessageSender:f,lastMessageOutgoingStatus:k,actionTargetMessage:A,actionTargetChatId:D,draft:_,messageListType:R,animationLevel:P,lastSyncTime:F,openChat:U,focusLastMessage:B})=>{const q=Object(a.q)(null),[H,$,Y]=Object(N.a)(),{lastMessage:V,typingStatus:K}=d||{},z=V&&Object(u.cb)(V);Object(E.a)(t,z?V.replyToMessageId:void 0,A);const W=V&&!Object(u.L)(V)?Object(u.E)(V):void 0,X=Object(T.a)(V?Object(u.D)(V,"micro"):void 0);Object(a.o)(()=>{if(0===P)return;const e=q.current;if(c===h.Opacity)e.style.opacity="0",Object(v.b)(()=>{e.classList.add("animate-opacity"),e.style.opacity="1"});else{if(c!==h.Move)return;e.style.transform=`translate3d(0, ${100*-r}%, 0)`,Object(v.b)(()=>{e.classList.add("animate-transform"),e.style.transform=""})}setTimeout(()=>{Object(v.b)(()=>{e.classList.remove("animate-opacity","animate-transform"),e.style.opacity="",e.style.transform=""})},200+s.c)},[P,r,c]);const G=Object(a.m)(()=>{U({id:t}),o&&"thread"===R&&B()},[o,R,U,t,B]),Q=Object(y.a)({chat:d,privateChatUser:m,handleDelete:$,folderId:n,isPinned:l}),J=Object(p.a)();if(!d)return;const Z=Object(j.a)("Chat chat-item-clickable",Object(u.kb)(t)?"private":"group",o&&!i.f&&"selected");return a.a.createElement(L.a,{ref:q,className:Z,style:e,ripple:!i.f,contextActions:Q,onClick:G},a.a.createElement(C.a,{chat:d,user:m,withOnlineStatus:!0,isSavedMessages:m&&m.isSelf,lastSyncTime:F}),a.a.createElement("div",{className:"info"},a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,Object(O.a)(Object(u.l)(d,m))),d.isVerified&&a.a.createElement(M.a,null),d.isMuted&&a.a.createElement("i",{className:"icon-muted-chat"}),d.lastMessage&&a.a.createElement(I.a,{message:d.lastMessage,outgoingStatus:k})),a.a.createElement("div",{className:"subtitle"},function(){if(K&&V&&K.timestamp>1e3*V.date)return a.a.createElement(w.a,{typingStatus:K});if(_&&_.text.length)return a.a.createElement("p",{className:"last-message"},a.a.createElement("span",{className:"draft"},J("Draft")),Object(O.a)(_.text));if(!V)return;if(z){const e=d&&(Object(u.ib)(d)||V.senderId===V.chatId)?d:f;return a.a.createElement("p",{className:"last-message"},Object(O.a)(Object(g.a)(V,e,b,A,D,{asPlain:!0})))}const e=Object(u.I)(t,f);return a.a.createElement("p",{className:"last-message"},e&&a.a.createElement("span",{className:"sender-name"},Object(O.a)(e)),function(e,t){if(!t)return Object(O.a)(Object(u.M)(e));return a.a.createElement("span",{className:"media-preview"},a.a.createElement("img",{src:t,alt:""}),Object(u.O)(e)&&a.a.createElement("i",{className:"icon-play"}),Object(O.a)(Object(u.M)(e,!0)))}(V,X||W))}(),a.a.createElement(x,{chat:d,isPinned:l}))),a.a.createElement(S.a,{isOpen:H,onClose:Y,chat:d}))}));!function(e){e.all="active",e.archived="archived"}(D||(D={}));t.a=Object(a.h)(Object(r.h)((e,{folderType:t,folderId:n})=>{const{chats:{listIds:a,byId:r,orderedPinnedIds:s},users:{byId:i},lastSyncTime:o}=e,{chatId:l,threadId:u}=Object(d.y)(e)||{},m="folder"!==t?D[t]:void 0,h=n?Object(d.i)(e,n):void 0;return{chatsById:r,usersById:i,currentChatId:l,lastSyncTime:o,...m?{listIds:a[m],orderedPinnedIds:s[m]}:{chatFolder:h},isInDiscussionThread:u!==c.MAIN_THREAD_ID}},(e,t)=>Object(l.l)(t,["loadMoreChats","preloadTopChatMessages"]))(({folderType:e,folderId:t,noChatsText:n="Chat list is empty.",chatFolder:r,chatsById:c,usersById:d,listIds:p,currentChatId:g,orderedPinnedIds:O,lastSyncTime:v,isInDiscussionThread:j,loadMoreChats:E,preloadTopChatMessages:y})=>{const[N,T]=Object(a.p)(()=>"folder"===e&&r?Object(u.Ab)(c,d,r):[p,O],[e,c,d,r,p,O]),[C,M]=Object(a.p)(()=>{if(!N||"folder"===e&&!r)return[];const t=Object(u.zb)(c,N,T,e),n=[...t.pinnedChats,...t.otherChats],a=n.map(({id:e})=>e);return[n.reduce((e,t,n)=>(e[t.id]=n,e),{}),a]},[N,T,e,r,c]),w=Object(o.a)(C),I=C&&w?Object(l.i)(C,(e,t)=>e-(void 0!==w[t]?w[t]:1/0)):{},S=Object(a.m)(()=>{E({listType:"archived"===e?"archived":"active"})},[E,e]),[L,k]=Object(m.a)(v?S:void 0,M,void 0,s.j,"all"===e&&!s.a),A=L&&Object(u.zb)(c,L,T,e);Object(a.n)(()=>{v&&"all"===e&&y()},[v,e,y]);const x=function(e){const t=Object(a.m)(t=>e[t]<0,[e]),n=Object(a.m)(t=>e[t]>0,[e]),r=Object.keys(e).map(Number),c=r.filter(t).length,s=r.filter(n).length;return Object(a.m)(a=>{const r=e[a];return 0===r?h.None:r===1/0||r===-1/0||t(a)&&c<=s||n(a)&&sa.a.createElement(_,{key:n,teactOrderKey:r,chatId:n,isPinned:!0,folderId:t,isSelected:n===g&&!j,animationType:x(n),orderDiff:I[n],style:`top: ${(e+r)*s.h}px;`})),A.otherChats.map((e,r)=>a.a.createElement(_,{key:e.id,teactOrderKey:Object(u.j)(e),chatId:e.id,folderId:t,isSelected:e.id===g&&!j,animationType:x(e.id),orderDiff:I[e.id],style:`top: ${(n+r)*s.h}px;`})))}():L&&!L.length?a.a.createElement("div",{className:"no-results"},n):a.a.createElement(f.a,{key:"loading"}))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var a=n(0),r=n(5),c=n(147),s=n(37),i=n(2),o=n(3),l=n(8),u=n(110);var d=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:r})=>{const c=Object(a.m)(()=>{t&&n({id:t.id})},[t,n]);return t?a.a.createElement(u.a,{className:Object(l.a)("UserLink",e),onClick:c},r):r});var m=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:r})=>{const c=Object(a.m)(()=>{t&&r({chatId:t.chatId,messageId:t.id})},[r,t]);return t?a.a.createElement(u.a,{className:Object(l.a)("MessageLink",e),onClick:c},n):n});var h=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:r})=>{const c=Object(a.m)(()=>{t&&n({id:t})},[t,n]);return t?a.a.createElement(u.a,{className:Object(l.a)("ChatLink",e),onClick:c},r):r});function b(e,t,n,i,o,l={}){if(!e.content.action)return[];const{text:u}=e.content.action,d=[],b={...l,maxTextLength:16};let g,O=p(u,"%action_origin%",t?!l.isEmbedded&&(v=t,j=l.asPlain,Object(r.eb)(v)?function(e,t){const n=Object(c.a)(Object(r.l)(e));return t?n:a.a.createElement(h,{className:"action-link",chatId:e.id},e&&Object(s.a)(n))}(v,j):f(v,j))||" ":"User");var v,j;return g=O.pop(),d.push(...O),O=p(g,"%target_user%",n?f(n,l.asPlain):"User"),g=O.pop(),d.push(...O),O=p(g,"%message%",i?function(e,t={}){const n=Object(r.M)(e),{photo:i,video:o,document:l,sticker:u}=Object(r.v)(e),d=n&&!i&&!o&&!l&&!u;let h=Object(c.a)(n,t.maxTextLength);i?h="a photo":o?h=o.isGif?"a GIF":"a video":l?h="a document":u&&(h=`«${n}»`);if(t.asPlain)return d?`«${h}»`:h;if(d)return a.a.createElement("span",null,"«",a.a.createElement(m,{className:"action-link",message:e},Object(s.a)(h)),"»");return a.a.createElement(m,{className:"action-link",message:e},Object(s.a)(h))}(i,b):"a message"),g=O.pop(),d.push(...O),O=p(g,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),g=O.pop(),d.push(...O),O=p(g,"%target_chat%",o?function(e,t){if(t)return"another chat";return a.a.createElement(h,{className:"action-link",chatId:e},"another chat")}(o,l.asPlain):"another chat"),d.push(...O),l.asPlain?d.join("").trim():d}function f(e,t){const n=Object(c.a)(Object(r.Y)(e));return t?n:a.a.createElement(d,{className:"action-link",sender:e},e&&Object(s.a)(n))}function p(e,t,n){const a=e.indexOf(t);if(a<0||!n)return[e];const r=[];return r.push(e.substring(0,a)),r.push(n),r.push(e.substring(a+t.length)),r}},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var a=n(0),r=n(4),c=n(1),s=n(5),i=n(46);var o=n(7),l=n(124),u=n(28);const d=/[^@_\d\wа-яё]+/i;function m(e,t,n,m=c.u,h,b,f){const[p,g,O]=Object(u.a)(),[v,j]=Object(a.r)(""),[E,y]=Object(a.r)([]),N=Object(a.m)(e=>{if(h&&f)return h.filter(({userId:t})=>{const n=f[t];return!(t===b||!n)&&(!e||function(e,t){const n=t.username.toLowerCase(),a=Object(s.Y)(t),r=a&&a.toLowerCase(),c=e.toLowerCase();return n.startsWith(c)||r&&Object(i.a)(r,c)}(e,n))})},[h,b,f]);Object(a.n)(()=>{if(!e||!t.length)return void O();const n=function(e){const t=document.createElement("div");t.innerHTML=e;const n=t.innerText,a=n[n.length-1],r=n.split(d).pop();if(!n.length||d.test(a)||!r||!r.startsWith("@"))return;return r}(t);if(n){const e=n?n.substr(1):"",t=N(e);t&&t.length?(g(),j(e),y(t)):O()}else O()},[e,t,N,g,O]);const T=Object(a.m)((e,a=!1)=>{if(!e.username&&!Object(s.X)(e))return;const c=e.username?"@"+e.username:`${Object(s.X)(e)}`,i=t.lastIndexOf("@");if(-1!==i){n(`${t.substr(0,i)}${c} `);const e=document.getElementById(m);o.f||requestAnimationFrame(()=>{Object(l.a)(e,a)})}O()},[t,m,n,O]);return{isMentionMenuOpen:p,mentionFilter:v,closeMentionMenu:O,insertMention:T,mentionFilteredMembers:E}}},,function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},function(e,t,n){},,,function(e,t,n){},,function(e,t,n){},function(e,t,n){},,,,,,,,,,,,function(e,t,n){},,,,,,,,function(e,t,n){},function(e,t,n){},function(e,t,n){}])]); -//# sourceMappingURL=0.6531d7c910f326b2774d.js.map \ No newline at end of file +(window.webpackJsonp=window.webpackJsonp||[]).push([[0],Array(94).concat([function(e,t,n){"use strict";var a=n(11),r=n(31),c=n(103);t.a=()=>{const e=Object(r.a)();return Object(c.a)(()=>a.a(e),[e]),a.b}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(8),s=n(133),i=n(163),o=n(35),l=n(47),u=n(34);n(197);t.a=e=>{const{ref:t,icon:n,className:d,style:m,children:h,disabled:b,ripple:f,narrow:p,inactive:g,focus:O,destructive:v,multiline:j,contextActions:E,onClick:y}=e;let N=Object(a.q)(null);t&&(N=t);const{isContextMenuOpen:T,contextMenuPosition:C,handleBeforeContextMenu:M,handleContextMenu:w,handleContextMenuClose:I,handleContextMenuHide:S}=Object(s.a)(N,!E),L=Object(a.m)(()=>N.current,[]),k=Object(a.m)(()=>N.current.closest(".custom-scroll"),[]),A=Object(a.m)(()=>N.current.querySelector(".ListItem-context-menu .bubble"),[]),{positionX:x,positionY:D,style:_}=Object(i.a)(C,L,k,A),R=Object(a.m)(e=>{!b&&y&&y(e)},[b,y]),P=Object(a.m)(e=>{g||r.k||(!E||2!==e.button&&y||M(e),0===e.button&&(y?R(e):w(e)))},[g,E,y,M,w,R]),F=Object(c.a)("ListItem no-selection",d,f&&"has-ripple",p&&"narrow",b&&"disabled",g&&"inactive",C&&"has-menu-open",O&&"focus",v&&"destructive",j&&"multiline");return a.a.createElement("div",{ref:N,className:F,style:m},a.a.createElement("div",{className:"ListItem-button",role:"button",tabIndex:0,onClick:!g&&r.k?R:void 0,onMouseDown:P,onContextMenu:!g&&E?w:void 0},n&&a.a.createElement("i",{className:"icon-"+n}),j&&a.a.createElement("div",{className:"multiline-item"},h),!j&&h,!b&&!g&&f&&a.a.createElement(o.a,null)),E&&void 0!==C&&a.a.createElement(l.a,{isOpen:T,positionX:x,positionY:D,style:_,className:"ListItem-context-menu",autoClose:!0,onClose:I,onCloseAnimationEnd:S},E.map(e=>a.a.createElement(u.a,{key:e.title,icon:e.icon,destructive:e.destructive,disabled:!e.handler,onClick:e.handler},e.title))))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return o}));var a=n(0),r=n(9),c=n(43);function s({rootRef:e,throttleMs:t,debounceMs:n,shouldSkipFirst:s,margin:i,threshold:o,isDisabled:l},u){const d=Object(a.q)(),m=Object(a.q)(),h=Object(a.q)(),b=Object(a.q)();m.current=u;const f=Object(a.m)(()=>{h.current=!0},[]),p=Object(a.m)(()=>{h.current=!1,b.current&&(b.current(),b.current=void 0)},[]);Object(c.a)(f,p),Object(a.n)(()=>{if(!l)return()=>{d.current&&(d.current.observer.disconnect(),d.current.callbacks.clear(),d.current=void 0)}},[l]);return{observe:Object(a.m)((a,c)=>{d.current||function(){const a=new Map,c=new Map,l=()=>{const e=Array.from(c.values());e.forEach(t=>{const n=a.get(t.target);n&&n(t,e)}),m.current&&m.current(e),c.clear()},u=t?r.g:n?r.a:void 0,f=u?u(l,t||n,!s):l,p=new IntersectionObserver(e=>{e.forEach(e=>{c.set(e.target,e)}),h.current?b.current=()=>{f()}:f()},{root:e.current,rootMargin:i?i+"px":void 0,threshold:o});d.current={observer:p,callbacks:a}}();const l=d.current;return l.observer.observe(a),c&&l.callbacks.set(a,c),()=>{c&&l.callbacks.delete(a),l.observer.unobserve(a)}},[l]),freeze:f,unfreeze:p}}function i(e,t,n){Object(a.n)(()=>t?t(e.current,n):void 0,[])}function o(e,t,n){const[r,c]=Object(a.r)(!t);return i(e,t,e=>{c(e.isIntersecting),n&&n(e)}),r}},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(48),s=n(31);t.a=(e,t=!1,n=r.ApiMediaFormat.BlobUrl,i,o)=>{const l=e?c.c(e):void 0,u=Object(s.a)();return Object(a.n)(()=>{if(!t&&e&&!l){const t=Date.now();c.b(e,n).then(()=>{const e=Date.now()-t;!o||e>=o?u():setTimeout(u,o-e)})}},[t,e,l,n,i,u,o]),l}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(19),s=n(6),i=n(5),o=n(37),l=n(3),u=n(94),d=n(101),m=n(123),h=n(148);t.a=Object(a.h)(Object(r.h)((e,{userId:t,forceShowSelf:n})=>{const{lastSyncTime:a}=e,r=Object(s.Db)(e,t);return{lastSyncTime:a,user:r,isSavedMessages:!n&&r&&r.isSelf,areMessagesLoaded:Boolean(Object(s.m)(e,t))}},(e,t)=>Object(l.l)(t,["loadFullUser","openMediaViewer"]))(({typingStatus:e,avatarSize:t="medium",status:n,withMediaViewer:r,withUsername:s,withFullInfo:l,withUpdatingStatus:b,noStatusOrTyping:f,user:p,isSavedMessages:g,areMessagesLoaded:O,lastSyncTime:v,loadFullUser:j,openMediaViewer:E})=>{const{id:y}=p||{},N=Object(i.Y)(p);Object(a.n)(()=>{l&&v&&y&&j({userId:y})},[y,j,v,l]);const T=Object(a.m)((e,n)=>{p&&n&&(e.stopPropagation(),E({avatarOwnerId:p.id,origin:"jumbo"===t?c.h.ProfileAvatar:c.h.MiddleHeaderAvatar}))},[p,t,E]),C=Object(u.a)();if(p)return a.a.createElement("div",{className:"ChatInfo"},a.a.createElement(d.a,{key:p.id,size:t,user:p,isSavedMessages:g,onClick:r?T:void 0}),a.a.createElement("div",{className:"info"},g?a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,C("SavedMessages"))):a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,N&&Object(o.a)(N)),p&&p.isVerified&&a.a.createElement(m.a,null)),(n||!g&&!f)&&(n?a.a.createElement("span",{className:"status"},n):b&&!O?a.a.createElement("span",{className:"status"},C("Updating")):p?e?a.a.createElement(h.a,{typingStatus:e}):a.a.createElement("div",{className:"status "+(Object(i.wb)(p)?"online":"")},s&&p.username&&a.a.createElement("span",{className:"handle"},p.username),a.a.createElement("span",{className:"user-status"},Object(i.Z)(p,C))):void 0)))}))},function(e,t,n){"use strict";var a=n(0),r=n(50);var c=n(8),s=n(43),i=n(29),o=n(52),l=n(94),u=n(25),d=n(113);n(140);t.a=e=>{const{title:t,className:n,isOpen:m,header:h,hasCloseButton:b,noBackdrop:f,children:p,onClose:g,onCloseAnimationEnd:O,onEnter:v}=e,{shouldRender:j,transitionClassNames:E}=Object(i.a)(m,O),y=Object(a.q)(null);Object(a.n)(()=>m?Object(r.a)({onEsc:g,onEnter:v}):void 0,[m,g,v]),Object(a.n)(()=>m&&y.current?function(e){function t(t){if("Tab"!==t.key)return;t.preventDefault(),t.stopPropagation();const n=Array.from(e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(!n.length)return;const a=n.findIndex(e=>e.isSameNode(document.activeElement));let r=0;a>=0&&(r=t.shiftKey?a>0?a-1:n.length-1:a{document.removeEventListener("keydown",t,!1)}}(y.current):void 0,[m]),Object(o.a)(([e])=>(document.body.classList.toggle("has-open-dialog",m),(m||!m&&void 0!==e)&&Object(s.b)(200),()=>{document.body.classList.remove("has-open-dialog")}),[m]);const N=Object(l.a)();if(!j)return;const T=Object(c.a)("Modal",n,E,f&&"transparent-backdrop");return a.a.createElement(d.a,null,a.a.createElement("div",{ref:y,className:T,tabIndex:-1,role:"dialog"},a.a.createElement("div",{className:"modal-container"},a.a.createElement("div",{className:"modal-backdrop",onClick:g}),a.a.createElement("div",{className:"modal-dialog"},h||(t?a.a.createElement("div",{className:"modal-header"},b&&a.a.createElement(u.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:N("Close"),onClick:g},a.a.createElement("i",{className:"icon-close"})),a.a.createElement("div",{className:"modal-title"},t)):void 0),a.a.createElement("div",{className:"modal-content custom-scroll"},p)))))}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(1),s=n(7),i=n(31),o=n(38),l=n(8),u=n(43);n(182);const d={slide:450,"mv-slide":400,"slide-fade":400,"zoom-fade":150,"scroll-slide":500,fade:150,"slide-layers":s.f?450:300,"push-slide":300,reveal:350},m=Symbol("CLEANED_UP");t.a=Object(r.h)(e=>{const{animationLevel:t}=e.settings.byKey;return{animationLevel:t}})(({ref:e,activeKey:t,name:n,direction:r="auto",renderCount:s,shouldRestoreHeight:h,shouldCleanup:b,id:f,className:p,onStart:g,onStop:O,children:v,animationLevel:j})=>{let E=Object(a.q)(null);e&&(E=e);const y=Object(a.q)({}),N=Object(o.a)(t),T=Object(a.q)(),C=Object(i.a)(),M=void 0!==N&&t!==N;!s&&M&&(y.current={[N]:y.current[N]}),y.current[t]=v,Object(a.o)(()=>{function e(){b&&(y.current={[N]:m},C())}const a=E.current,i=a.children;if(1===i.length&&!M)return void i[0].classList.add("active");const o=Array.from(a.childNodes);if(!M||!o.length)return;T.current&&(clearTimeout(T.current),T.current=void 0);const l=-1===r||"auto"===r&&N>t||"inverse"===r&&N{e instanceof HTMLElement&&(e.classList.remove("from","through","to"),e.classList.toggle("active",t===v))}),void e();if(o.forEach((e,t)=>{e instanceof HTMLElement&&(e.classList.remove("active"),e.classList.toggle("from",t===p),e.classList.toggle("through",t>p&&tv),e.classList.toggle("to",t===v))}),"scroll-slide"===n){const e=a.offsetWidth;a.scrollBy({left:v>p?e:-e,behavior:"smooth"})}j>0&&Object(u.b)(d[n]+c.c),requestAnimationFrame(()=>{a.classList.add("animating"),T.current=window.setTimeout(()=>{requestAnimationFrame(()=>{if(a.classList.remove("animating","backwards"),o.forEach((e,t)=>{e instanceof HTMLElement&&(e.classList.remove("from","through","to"),e.classList.toggle("active",t===v))}),"scroll-slide"===n&&(a.scrollLeft=t*a.offsetWidth),h){const e=a.querySelector(".active");e&&(e.style.height="auto",a.style.height=e.clientHeight+"px")}e(),O&&O()})},d[n]+c.c),g&&g()})},[t,N,M,r,n,g,O,s,h,b,j,C]),Object(a.o)(()=>{if(h){const e=E.current,t=e.querySelector(".active")||e.querySelector(".from");t&&(t.style.height="auto",e.style.height=t.clientHeight+"px")}},[h,v]);const w=y.current,I=Object.keys(s?new Array(s).fill(void 0):w).map(Number).map(e=>{const n=w[e];return"function"==typeof n?a.a.createElement("div",{key:e},n(e===t,e===N)):void 0}),S=Object(l.a)("Transition",p,0===j&&"scroll-slide"===n?"slide":n);return a.a.createElement("div",{ref:E,id:f,className:S},I)})},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(1),s=n(5),i=n(44),o=n(8),l=n(37),u=n(97),d=n(104),m=n(94);n(184);t.a=Object(a.h)(({className:e,size:t="large",chat:n,user:h,text:b,withOnlineStatus:f,isSavedMessages:p,lastSyncTime:g,onClick:O})=>{const v=h&&Object(s.ob)(h);let j;p||v||(h?j=Object(s.f)(h):n&&(j=Object(s.f)(n)));const E=Object(u.a)(j,!1,r.ApiMediaFormat.DataUri,g),{shouldRenderFullMedia:y,transitionClassNames:N}=Object(d.a)(E,"slow");Object(m.a)();let T="";if(p)T=a.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(v)T=a.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(y)T=a.a.createElement("img",{src:E,className:N+" avatar-media",alt:"",decoding:"async"});else if(h){const e=Object(s.Y)(h);T=e?Object(i.c)(e,2):void 0}else if(n){const e=Object(s.l)(n);T=e&&Object(i.c)(e,Object(s.kb)(n.id)?2:1)}else b&&(T=Object(i.c)(b,2));const C=!p&&h&&Object(s.wb)(h),M=Object(o.a)("Avatar size-"+t,e,"color-bg-"+Object(s.W)(h||n),p&&"saved-messages",v&&"deleted-account",f&&C&&"online",O&&"interactive",!p&&!y&&"no-photo"),w=Object(a.m)(e=>{O&&O(e,p||y)},[O,p,y]),I=(h||n)&&(h||n).id;return a.a.createElement("div",{className:M,onClick:w,"data-test-sender-id":c.E?I:void 0},"string"==typeof T?Object(l.a)(T,["jumbo"===t?"hq_emoji":"emoji"]):T)})},function(e,t,n){"use strict";var a=n(19),r=n(0),c=n(9),s=n(146);t.a=({ref:e,className:t,onLoadMore:n,onScroll:i,items:o,itemSelector:l=".ListItem",preloadBackwards:u=20,sensitiveArea:d=800,noScrollRestore:m=!1,noFastList:h,cacheBuster:b,children:f})=>{let p=Object(r.q)(null);e&&(p=e);const g=Object(r.q)({}),[O,v]=Object(r.p)(()=>n?[Object(c.a)(()=>n({direction:a.e.Backwards}),1e3,!0,!1),Object(c.a)(()=>n({direction:a.e.Forwards}),1e3,!0,!1)]:[],[n,o]);Object(r.n)(()=>{if(!O)return;if(u>0&&(!o||o.length{const e=p.current,t=g.current;if(t.listItemElements=e.querySelectorAll(l),m)return;let n;if(t.currentAnchor&&Array.from(t.listItemElements).includes(t.currentAnchor)){const{scrollTop:a}=e;n=a+(t.currentAnchor.getBoundingClientRect().top-t.currentAnchorTop)}else{const e=t.listItemElements[0];e&&e.offsetParent&&(t.currentAnchor=e,t.currentAnchorTop=e.getBoundingClientRect().top)}Object(s.a)(e,n),t.isScrollTopJustUpdated=!0},[m,l,o,b]);const j=Object(r.m)(e=>{if(v&&O){const{listItemElements:e,isScrollTopJustUpdated:t,currentAnchor:n,currentAnchorTop:a}=g.current;if(t)return void(g.current.isScrollTopJustUpdated=!1);const r=e.length,c=p.current,{scrollTop:i,scrollHeight:o,offsetHeight:l}=c,u=i<=(r?e[0].offsetTop:0)+d,m=(r?e[r-1].offsetTop+e[r-1].offsetHeight:o)-(i+l)<=d;let h=!1;if(u){const t=e[0];if(t){const e=t.getBoundingClientRect().top,r=n&&n.offsetParent&&n!==t?n.getBoundingClientRect().top:e;n&&void 0!==a&&r>a&&(g.current.currentAnchor=t,g.current.currentAnchorTop=e,h=!0,Object(s.a)(c),v())}}if(m){const t=e[r-1];if(t){const e=t.getBoundingClientRect().top,r=n&&n.offsetParent&&n!==t?n.getBoundingClientRect().top:e;n&&void 0!==a&&r{const n=Object(a.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";var a=n(0),r=n(29);const c={fast:200,slow:350};t.a=(e,t="fast",n=!1)=>{const s=Boolean(e),i=!Object(a.q)(s).current&&!n,[o,l]=Object(a.r)(!s),{shouldRender:u,transitionClassNames:d}=Object(r.a)(s,void 0,!i,t);return Object(a.n)(()=>{u&&(i?setTimeout(()=>{l(!1)},c[t]):l(!1))},[i,u,t]),{shouldRenderThumb:o,shouldRenderFullMedia:u,transitionClassNames:d}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return o})),n.d(t,"d",(function(){return l})),n.d(t,"a",(function(){return u})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return p})),n.d(t,"h",(function(){return g})),n.d(t,"k",(function(){return O})),n.d(t,"i",(function(){return v})),n.d(t,"l",(function(){return j})),n.d(t,"g",(function(){return E})),n.d(t,"e",(function(){return y}));var a=n(5),r=n(49),c=n(7),s=n(1);const i="(max-height: 640px)",o=parseInt(getComputedStyle(document.documentElement).fontSize,10),l=200,u={width:640,height:640},d={width:100,height:100};let m;function h(e,t,n){const a=t||n?1.625:0;return(function(e){const t=e?30:29;return c.f?(m||(m=Math.min(t,Math.floor(.69*window.innerWidth)/o)),m):t}(e)-a)*o}function b({width:e,height:t,fromOwnMessage:n,isForwarded:a,isWebPagePhoto:r,isGif:c}){const s=t/e;return y(h(n,a,r),function(e,t){return e&&t&&t>=.75&&t<=1.25?20*o:27*o}(c,s),e,t)}function f(e,t){const n=window.matchMedia(i),{width:a,height:c}=r.a.get();let s=t&&n.matches?10:8.25;return e&&(s=n.matches?10:15),{width:a,height:c-s*o}}function p(e,t,n,r){const{width:c,height:s}=Object(a.S)(e)||d;return b({width:c,height:s,fromOwnMessage:t,isForwarded:n,isWebPagePhoto:r})}function g(e,t,n){const{width:r,height:c}=Object(a.ab)(e)||d;return b({width:r,height:c,fromOwnMessage:t,isForwarded:n,isGif:e.isGif})}function O(){return{width:2*o,height:2*o}}function v(e){return e?{width:3*o,height:3*o}:{width:3.375*o,height:3.375*o}}function j(e){const{width:t}=e;let{height:n}=e;"1258816259753933"===e.id&&(n=t);const a=n&&t&&n/t,r=(c.f?s.ub:s.tb)*o,i=a?r*a:r;return a&&i>r?{width:Math.round(r/a),height:r}:{width:r,height:i}}function E({width:e,height:t},n,a=!1){const{width:r,height:c}=f(n,a);return y(r,c,e,t)}function y(e,t,n,a){const r=a/n,c=Math.min(n,e);return Math.round(c*r)>t?{width:Math.round(t/r),height:t}:{width:c,height:Math.round(c*r)}}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(9),s=n(8),i=n(43),o=n(121);let l,u;async function d(){return l||(l=n.e(6).then(n.bind(null,181)),u=(await l).default),l}setTimeout(d,5e3);t.a=Object(a.h)(({className:e,id:t,animationData:n,play:l,playSegment:m,speed:h,noLoop:b,size:f,quality:p,isLowPriority:g,onLoad:O})=>{const[v,j]=Object(a.r)(),E=Object(a.q)(null),y=Object(a.q)(!1),N=Object(a.q)(!1),T=Object(a.q)();T.current=l;const C=Object(a.q)();C.current=m,Object(a.n)(()=>{if(v||!n)return;const e=()=>{if(!E.current)return;const e=new u(t,E.current,n,{noLoop:b,size:f,quality:p,isLowPriority:g},O);h&&e.setSpeed(h),j(e)};u?e():d().then(()=>{Object(c.b)(()=>{E.current&&e()})})},[v,n,t,g,b,O,p,f,h]),Object(a.n)(()=>()=>{v&&v.destroy()},[v]);const M=Object(a.m)((e=!1)=>{v&&(T.current||C.current)&&(C.current?v.playSegment(C.current):e?v.goToAndPlay(0):v.play())},[v]),w=Object(a.m)(()=>{v&&v.pause()},[v]),I=Object(a.m)(()=>{N.current=!0,v&&(y.current||(y.current=v.isPlaying()),w())},[v,w]),S=Object(a.m)(()=>{y.current&&M(),y.current=!1,N.current=!1},[M]),L=Object(a.m)(()=>{Object(c.b)(S)},[S]);Object(a.n)(()=>{v&&(l||m?N.current?y.current=!0:M(b):N.current?y.current=!1:w())},[v,l,m,b,M,w]),Object(i.a)(I,S),Object(o.a)(I,L);const k=Object(s.a)("AnimatedSticker",e,r.d&&l&&"is-playing"),A=f?`width: ${f}px; height: ${f}px;`:void 0;return a.a.createElement("div",{ref:E,className:k,style:A})})},function(e,t,n){"use strict";var a=n(0),r=n(94),c=n(99),s=n(25);t.a=Object(a.h)(({isOpen:e,onClose:t,onCloseAnimationEnd:n,header:i,text:o,textParts:l,confirmLabel:u="Confirm",confirmHandler:d,confirmIsDestructive:m,isButtonsInOneRow:h})=>{const b=Object(r.a)();return a.a.createElement(c.a,{className:"confirm",header:i,isOpen:e,onClose:t,onCloseAnimationEnd:n,onEnter:d},o&&o.split("\\n").map(e=>a.a.createElement("p",null,e)),l,a.a.createElement("div",{className:h?"dialog-buttons mt-2":""},a.a.createElement(s.a,{className:"confirm-dialog-button",isText:!0,onClick:d,color:m?"danger":"primary"},u),a.a.createElement(s.a,{className:"confirm-dialog-button",isText:!0,onClick:t},b("Cancel"))))})},function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(29);n(238);t.a=Object(a.h)(({text:e="Nothing found."})=>{const{transitionClassNames:t}=Object(c.a)(!0);return a.a.createElement("div",{className:Object(r.a)("NothingFound",t)},e)})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(0),r=n(103),c=n(31);function s(e,t){const n=void 0===t,s=Object(a.q)(n),i=Object(a.q)(),o=Object(c.a)();return Object(r.a)(()=>{n||(s.current=!1,i.current&&(clearTimeout(i.current),i.current=void 0))},e),Object(a.n)(()=>{if(n||s.current)return;const e=()=>{s.current=!0,o()};t>0?i.current=window.setTimeout(e,t):e()},e),s.current}},function(e,t,n){"use strict";var a=n(0),r=n(8);n(191);t.a=({children:e,className:t,onClick:n})=>{const c=Object(a.m)(e=>{e.preventDefault(),n(e)},[n]);return a.a.createElement("a",{href:"#",className:Object(r.a)("Link",t),onClick:n?c:void 0},e)}},function(e,t,n){"use strict";var a=n(0),r=n(7),c=n(4),s=n(9),i=n(48),o=n(31);t.a=(e,t=!1,n=c.ApiMediaFormat.BlobUrl,l,u)=>{const d=e?i.c(e):void 0,m=n===c.ApiMediaFormat.Stream||r.h&&n===c.ApiMediaFormat.Progressive,h=Object(o.a)(),[b,f]=Object(a.r)(d&&!m?1:0),p=Object(a.q)(),g=Object(a.p)(()=>Object(s.g)(e=>{(!u||Date.now()-p.current>u)&&f(e)},500,!0),[u]);return Object(a.n)(()=>{!t&&e&&(d?m&&setTimeout(()=>{f(.75)},1500):(f(0),p.current&&i.a(g),p.current=Date.now(),i.b(e,n,g).then(()=>{const e=Date.now()-p.current;p.current=void 0,!u||e>=u?h():setTimeout(h,u-e)})))},[t,e,d,n,l,h,m,u,g]),Object(a.n)(()=>{t&&p.current&&(i.a(g),f(0))},[g,t]),{mediaData:d,downloadProgress:b}}},function(e,t,n){"use strict";var a=n(0),r=n(8);n(208);const c={s:22,m:25,l:28,xl:20};t.a=Object(a.h)(({progress:e=0,size:t="l",square:n,transparent:s,noCross:i,onClick:o})=>{const l=c[t],u=l-4,d=l-1,m=2*u*Math.PI,h=Object(a.q)(null);Object(a.n)(()=>{if(!h.current)return;const t=h.current.firstElementChild,n=m-Math.min(Math.max(.05,e),1)*m;t?t.firstElementChild.setAttribute("stroke-dashoffset",n.toString()):h.current.innerHTML=`\n \n `},[h,m,d,u,e]);const b=Object(r.a)("ProgressSpinner size-"+t,s&&"transparent",n&&"square",i&&"no-cross");return a.a.createElement("div",{ref:h,className:b,onClick:o})})},function(e,t,n){"use strict";var a=n(0),r=n(57);t.a=({containerId:e,className:t,children:n})=>{const c=Object(a.q)(document.createElement("div"));return Object(a.o)(()=>{const n=document.querySelector(e||"#portals");if(!n)return;const a=c.current;return t&&a.classList.add(t),n.appendChild(a),()=>{r.a.render(void 0,a),n.removeChild(a)}},[t,e]),r.a.render(n,c.current)}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(19),s=n(5),i=n(6),o=n(37),l=n(3),u=n(94),d=n(101),m=n(123),h=n(148);t.a=Object(a.h)(Object(r.h)((e,{chatId:t})=>{const{lastSyncTime:n}=e,a=Object(i.f)(e,t);return{lastSyncTime:n,chat:a,onlineCount:a?Object(i.n)(e,a):void 0,areMessagesLoaded:Boolean(Object(i.m)(e,t))}},(e,t)=>Object(l.l)(t,["loadFullChat","openMediaViewer"]))(({typingStatus:e,avatarSize:t="medium",withMediaViewer:n,withUsername:r,withFullInfo:i,withUpdatingStatus:l,withChatType:b,chat:f,onlineCount:p,areMessagesLoaded:g,lastSyncTime:O,loadFullChat:v,openMediaViewer:j})=>{const E=f&&Object(s.mb)(f),{id:y,isMin:N,isRestricted:T}=f||{};Object(a.n)(()=>{y&&!N&&i&&O&&v({chatId:y})},[y,N,O,i,v,E]);const C=Object(a.m)((e,n)=>{f&&n&&(e.stopPropagation(),j({avatarOwnerId:f.id,origin:"jumbo"===t?c.h.ProfileAvatar:c.h.MiddleHeaderAvatar}))},[f,t,j]),M=Object(u.a)();if(f)return a.a.createElement("div",{className:"ChatInfo"},a.a.createElement(d.a,{key:f.id,size:t,chat:f,onClick:n?C:void 0}),a.a.createElement("div",{className:"info"},a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,Object(o.a)(Object(s.l)(f))),f.isVerified&&a.a.createElement(m.a,null)),function(){if(l&&!g&&!T)return a.a.createElement("span",{className:"status"},M("Updating"));if(!f)return;if(e)return a.a.createElement(h.a,{typingStatus:e});if(b)return a.a.createElement("div",{className:"status"},M(Object(s.m)(f)));const t=r?f.username:void 0,n=function(e,t){const n=t(Object(s.m)(e)),{membersCount:a}=e;if(e.isRestricted)return"Channel"===n?"channel is inaccessible":"group is inaccessible";if(!a)return n;return t("Channel"===n?"Subscribers":"Members",a,"i")}(f,M),c=p?", "+M("OnlineCount",p,"i"):void 0;return a.a.createElement("div",{className:"status"},t&&a.a.createElement("span",{className:"handle"},t),a.a.createElement("span",{className:"group-status"},n),c&&a.a.createElement("span",{className:"online-status"},c))}()))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return l}));var a=n(19),r=n(43),c=n(9),s=n(55);let i=!1;function o(e,t,n,o=0,l=1500,u,d,m){if(u===a.b.Static)return void t.scrollIntoView({block:n});const{offsetTop:h}=t;if(void 0===u){const t=h-e.scrollTop;t<-l?e.scrollTop+=t+l:t>l&&(e.scrollTop+=t-l)}else u===a.b.Up?e.scrollTop=h+l:u===a.b.Down&&(e.scrollTop=Math.max(0,h-l));i=!0,Object(c.b)(()=>{Object(r.b)(600),function(e,t,n,a=0,r,c){const{offsetTop:o,offsetHeight:l}=t,{scrollTop:u,offsetHeight:d,scrollHeight:m}=e,h=!c&&e.dataset.normalHeight?Number(e.dataset.normalHeight):d;let b;switch(n){case"start":b=o-a-u;break;case"end":b=o+l+a-(u+h);break;case"nearest":case"center":b=l0){const e=m-(u+h);b=Math.min(b,e)}const f=e.scrollTop+b,p=r||250+Math.abs(b)/1500*350,g=Date.now();Object(s.b)(()=>{const t=Math.min((Date.now()-g)/p,1),n=b*(1-function(e){return 1-(1-e)**3.5}(t));return e.scrollTop=Math.round(f-n),i=t<1,i})}(e,t,n,o,d,m)})}function l(){return i}},,function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(20);n(215);var s=Object(a.h)(({id:e,label:t,subLabel:n,value:s,name:i,checked:o,disabled:l,hidden:u,isLoading:d,onChange:m})=>{const h=Object(r.a)("Radio",l&&"disabled",u&&"hidden-widget",d&&"loading");return a.a.createElement("label",{className:h},a.a.createElement("input",{type:"radio",name:i,value:s,id:e,checked:o,onChange:m,disabled:l||u}),a.a.createElement("div",{className:"Radio-main"},a.a.createElement("span",{className:"label"},t),n&&a.a.createElement("span",{className:"subLabel"},n)),d&&a.a.createElement(c.a,null))});t.a=Object(a.h)(({id:e,name:t,options:n,selected:r,disabled:c,loadingOption:i,onChange:o})=>{const l=Object(a.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]);return a.a.createElement("div",{id:e,className:"radio-group"},n.map(e=>a.a.createElement(s,{name:t,label:e.label,subLabel:e.subLabel,value:e.value,checked:e.value===r,hidden:e.hidden,disabled:c,isLoading:i?i===e.value:void 0,onChange:l})))})},function(e,t,n){"use strict";var a=n(0),r=n(19),c=n(3),s=n(31),i=n(38);function o(e,t=0,n,a){const{length:c}=e,s=e.indexOf(t),i=n===r.e.Forwards?s:s+1||c,o=Math.max(0,i-a),l=i+a-1,u=e.slice(Math.max(0,o),l+1);let d,m;switch(n){case r.e.Forwards:d=i>0,m=o>=0;break;case r.e.Backwards:d=i{const d=Object(a.q)(),m=Object(a.q)((()=>{if(!t||d.current)return;const{newViewportIds:e}=o(t,t[0],r.e.Forwards,l);return e})()),h=Object(s.a)(),b=Object(i.a)(t),f=Object(i.a)(n);if(t&&!n&&(t!==b||n!==f)){const{offsetId:e=t[0],direction:n=r.e.Forwards}=d.current||{},{newViewportIds:a}=o(t,e,n,l);m.current&&Object(c.a)(m.current,a)||(m.current=a)}Object(a.n)(()=>{if(t&&!n&&e&&u){const t=m.current;e({offsetId:t[t.length-1]})}},[t,n,e,u]);const p=Object(a.m)(({direction:n})=>{const a=m.current,s=a?n===r.e.Backwards?a[a.length-1]:a[0]:void 0;if(!t)return void(e&&e({offsetId:s}));d.current={...d.current,direction:n,offsetId:s};const{newViewportIds:i,areSomeLocal:u,areAllLocal:b}=o(t,s,n,l);!u||a&&Object(c.a)(a,i)||(m.current=i,h()),!b&&e&&e({offsetId:s})},[t,l,e,h]);return n?[t]:[m.current,p]}},function(e,t,n){"use strict";var a=n(0),r=n(4),c=n(1),s=n(105),i=n(96),o=n(97),l=n(104),u=n(28),d=n(106);n(213);t.a=({sticker:e,isInline:t=!1,observeIntersection:n,lastSyncTime:m})=>{const h=Object(a.q)(null),[b,f]=Object(u.a)(),p="sticker"+e.id,g=Object(i.b)(h,n),O=Object(o.a)(p+"?size=m",!g,r.ApiMediaFormat.BlobUrl,m),{transitionClassNames:v}=Object(l.a)(O,"slow"),j=Object(o.a)(p,!g,r.ApiMediaFormat.Lottie,m),E=Boolean(j),[y,N]=Object(a.r)(String(Math.random())),T=Object(a.m)(()=>{N(String(Math.random()))},[]);let C;C=t?.5*Object(s.l)(e).width:c.zb;const M=`width: ${C}px; height: ${C}px;`;return a.a.createElement("div",{ref:h,className:"AnimatedEmoji media-inner",style:M,onClick:T},O&&!b&&a.a.createElement("img",{src:O,className:v,alt:""}),E&&a.a.createElement(d.a,{key:p,id:p,animationData:j,size:C,quality:1,play:g&&y,noLoop:!0,onLoad:f}))}},,function(e,t,n){"use strict";var a=n(0);t.a=(e,t)=>{Object(a.n)(()=>(document.hasFocus()||e(),window.addEventListener("blur",e),window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t),window.removeEventListener("blur",e)}),[e,t])}},function(e,t,n){"use strict";let a;n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return r})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Left=2]="Left",e[e.Right=3]="Right"}(a||(a={}));function r(e,t){let n,r=!1;function c(e){t.excludedClosestSelector&&(e.target.matches(t.excludedClosestSelector)||e.target.closest(t.excludedClosestSelector))||(n=e,"mousedown"===e.type?(document.addEventListener("mousemove",i),document.addEventListener("mouseup",s)):"touchstart"===e.type&&(document.addEventListener("touchmove",i),document.addEventListener("touchend",s),document.addEventListener("touchcancel",s),"touches"in e&&(void 0===e.pageX&&(e.pageX=e.touches[0].pageX),void 0===e.pageY&&(e.pageY=e.touches[0].pageY))),document.body.classList.add("no-selection"),t.withCursor&&document.body.classList.add("cursor-grabbing"),t.onCapture&&t.onCapture(e))}function s(e){n&&(t.withCursor&&document.body.classList.remove("cursor-grabbing"),document.body.classList.remove("no-selection"),document.removeEventListener("mouseup",s),document.removeEventListener("mousemove",i),document.removeEventListener("touchcancel",s),document.removeEventListener("touchend",s),document.removeEventListener("touchmove",i),n=void 0,r?t.onRelease&&t.onRelease(e):t.onClick&&t.onClick(e)),r=!1}function i(e){if(n){"touchmove"===e.type&&"touches"in e&&(void 0===e.pageX&&(e.pageX=e.touches[0].pageX),void 0===e.pageY&&(e.pageY=e.touches[0].pageY));const c=e.pageX-n.pageX,s=e.pageY-n.pageY;(Math.abs(c)>=15||Math.abs(s)>=15)&&(r=!0),t.onDrag&&t.onDrag(e,n,{dragOffsetX:c,dragOffsetY:s}),t.onSwipe&&function(e,t,n,r){const c=Math.abs(t),s=Math.abs(n);if(t&&n){if(Math.max(c,s)/Math.min(c,s)<2)return}c>=50?r(e,t<0?a.Left:a.Right):s>=50&&r(e,n<0?a.Up:a.Down)}(e,c,s,t.onSwipe)}}return e.addEventListener("mousedown",c),e.addEventListener("touchstart",c,{passive:!0}),()=>{e.removeEventListener("mousedown",c),e.removeEventListener("touchstart",c)}}},function(e,t,n){"use strict";var a=n(0);n(192);t.a=()=>a.a.createElement("span",{className:"VerifiedIcon"})},function(e,t,n){"use strict";var a=n(1);t.a=e=>{e.play().catch(e=>{a.o&&console.warn(e)})}},function(e,t,n){"use strict";var a=n(0),r=n(9),c=n(150);t.a=(e=!1)=>{const[t,n]=Object(a.r)(!e),[s,i]=Object(a.r)(0),o=Object(a.p)(()=>Object(r.a)(n,200,!1,!0),[]),l=Object(a.m)(e=>{const t=e.currentTarget;Object(c.a)(t)||(t.buffered.length&&i(t.buffered.end(0)/t.duration),o(t.readyState>=3||t.currentTime>0))},[o]);return{isBuffered:t,bufferedProgress:s,bufferingHandlers:{onLoadedData:l,onPlaying:l,onLoadStart:l,onPause:l,onTimeUpdate:l,onProgress:l},checkBuffering(e){o(e.readyState>=3)}}}},function(e,t,n){"use strict";function a(e,t){if(!t&&e===document.activeElement)return;const n=window.getSelection(),a=document.createRange();e.lastChild&&e.lastChild.nodeValue?(a.setStart(e.lastChild,e.lastChild.nodeValue.length),n.removeAllRanges(),n.addRange(a)):e.focus()}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(4),r=n(7);const c={B:a.ApiMessageEntityTypes.Bold,STRONG:a.ApiMessageEntityTypes.Bold,I:a.ApiMessageEntityTypes.Italic,EM:a.ApiMessageEntityTypes.Italic,U:a.ApiMessageEntityTypes.Underline,S:a.ApiMessageEntityTypes.Strike,STRIKE:a.ApiMessageEntityTypes.Strike,DEL:a.ApiMessageEntityTypes.Strike,CODE:a.ApiMessageEntityTypes.Code,PRE:a.ApiMessageEntityTypes.Pre,BLOCKQUOTE:a.ApiMessageEntityTypes.Blockquote};function s(e){const t=document.createElement("div");t.innerHTML=function(e){let t=e.slice(0);r.c||(t=t.replace(/]+alt="([^"]+)"[^>]*>/gm,"$1"));return t=t.replace(/<\/?span([^>]*)?>/g,""),t=t.replace(/ /g," "),t=t.replace(/]*)?>/g,"\n"),t=t.replace(/<\/div>(\s*)
/g,"\n"),t=t.replace(/
/g,"\n"),t=t.replace(/<\/div>/g,""),t=t.replace(/^`{3}(.*[\n\r][^]*?^)`{3}/gm,"
$1
"),t=t.replace(/[`]{3}([^`]+)[`]{3}/g,"
$1
"),t=t.replace(/[`]{1}([^`\n]+)[`]{1}/g,"$1"),t=t.replace(/[*]{2}([^*\n]+)[*]{2}/g,"$1"),t=t.replace(/[*]{1}([^*\n]+)[*]{1}/g,"$1"),t=t.replace(/[~]{2}([^~\n]+)[~]{2}/g,"$1"),t}(e);const n=t.innerText.trim().replace(/\u200b+/g,"").slice(0,4096);let s=0,i=0;const o=[];function l(e){const{index:t,entity:r}=function(e,t,n){const r=function(e){if(c[e.nodeName])return c[e.nodeName];if("A"===e.nodeName){const t=e;return t.dataset.entityType===a.ApiMessageEntityTypes.MentionName?a.ApiMessageEntityTypes.MentionName:t.href.startsWith("mailto:")?a.ApiMessageEntityTypes.Email:t.href.startsWith("tel:")?a.ApiMessageEntityTypes.Phone:t.href!==t.textContent?a.ApiMessageEntityTypes.TextUrl:a.ApiMessageEntityTypes.Url}if("SPAN"===e.nodeName)return e.dataset.entityType;return}(e);if(!r||!e.textContent)return{index:n,entity:void 0};const s=t.indexOf(e.textContent,n),i=s>=0?s:n,o=t.substring(0,i).length,{length:l}=t.substring(i,i+e.textContent.length);let u,d;r===a.ApiMessageEntityTypes.TextUrl&&(u=e.href);r===a.ApiMessageEntityTypes.MentionName&&(d=Number(e.dataset.userId));return{index:i,entity:{type:r,offset:o,length:l,...u&&{url:u},...d&&{userId:d}}}}(e,n,s);r?(s=t,o.push(r)):e.textContent&&(s+=e.textContent.length),e.hasChildNodes()&&i<=3&&(i+=1,Array.from(e.childNodes).forEach(l))}return Array.from(t.childNodes).forEach(e=>{i=1,l(e)}),{text:n,entities:o.length?o:void 0}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var a=n(0),r=n(29),c=n(8),s=n(42),i=n(38),o=n(28);n(203);var l=Object(a.h)(({isQuick:e,onFileSelect:t})=>{const[n,r,s]=Object(o.a)(),i=Object(c.a)("DropTarget",n&&"hovered");return a.a.createElement("div",{className:i,onDrop:t,onDragEnter:()=>{r()},onDragLeave:e=>{const{relatedTarget:t}=e;t&&e.stopPropagation(),s()}},a.a.createElement("div",{className:"target-content"},a.a.createElement("div",{className:"icon icon-"+(e?"photo":"document")}),a.a.createElement("div",{className:"title"},"Drop files here to send them"),a.a.createElement("div",{className:"description"},e?"in a quick way":"without compression")))});n(204);let u;!function(e){e.None="none",e.Document="document",e.QuickFile="quick_file"}(u||(u={}));t.b=Object(a.h)(({isOpen:e,withQuick:t,onHide:n,onFileSelect:o})=>{const u=Object(a.q)(null),d=Object(i.a)(t),{shouldRender:m,transitionClassNames:h}=Object(r.a)(e);Object(a.n)(()=>e?Object(s.a)(n):void 0,[e,n]);const b=Object(a.m)(e=>{const{dataTransfer:t}=e;t.files&&t.files.length>0&&(n(),o(Array.from(t.files),!1))},[o,n]),f=Object(a.m)(e=>{const{dataTransfer:t}=e;t.files&&t.files.length>0&&(n(),o(Array.from(t.files),!0))},[o,n]),p=Object(a.m)(e=>{e.stopPropagation();const{target:t,relatedTarget:a}=e;t.matches(".DropTarget, .DropArea")&&!a&&(u.current=window.setTimeout(()=>{n()},150))},[n]);if(!m)return;const g=Object(c.a)("DropArea",h);return a.a.createElement("div",{className:g,onDragLeave:p,onDragOver:()=>{u.current&&window.clearTimeout(u.current)},onDrop:n},a.a.createElement(l,{onFileSelect:b}),(t||d)&&a.a.createElement(l,{onFileSelect:f,isQuick:!0}))})},,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(37),o=n(8),l=n(94),u=n(101);n(185);t.a=Object(a.h)(Object(r.h)((e,{chatOrUserId:t})=>{if(!t)return{};return{chat:t?Object(c.f)(e,t):void 0,user:Object(s.kb)(t)?Object(c.Db)(e,t):void 0}})(({icon:e,title:t,isMinimized:n,canClose:r,onClick:c,clickArg:d,chat:m,user:h,className:b})=>{let f,p;if(Object(l.a)(),e&&t)f=a.a.createElement("div",{className:"item-icon"},a.a.createElement("i",{className:"icon-"+e})),p=t;else if(m||h){f=a.a.createElement(u.a,{chat:m,user:h,size:"small",isSavedMessages:h&&h.isSelf});const e=!m||h&&!h.isSelf?Object(s.X)(h):Object(s.l)(m,h);p=e?Object(i.a)(e):void 0}const g=Object(o.a)("PickerSelectedItem",b,n&&"minimized",r&&"closeable");return a.a.createElement("div",{className:g,onClick:()=>c(d),title:n?p:void 0},f,!n&&a.a.createElement("div",{className:"item-name"},p),r&&a.a.createElement("div",{className:"item-remove"},a.a.createElement("i",{className:"icon-close"})))}))},function(e,t,n){"use strict";var a=n(0);t.a=(e,t)=>{Object(a.n)(()=>{const t=e.current;if(t)return t.addEventListener("wheel",n,{passive:!0}),()=>{t.removeEventListener("wheel",n)};function n(e){e.deltaX||(t.scrollLeft+=e.deltaY/4)}},[e,t])}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(9);t.a=(e,t,n,s)=>{const{loadMessage:i}=Object(r.d)(),o=Object(a.p)(()=>{const n=Object(c.g)(i,500,!0);return()=>{n({chatId:e,messageId:t,replyOriginForId:s})}},[i,e,t,s]);Object(a.n)(()=>{t&&!n&&o()})}},function(e,t,n){"use strict";var a=n(0),r=n(7);let c=0;t.a=(e,t)=>{const[n,s]=Object(a.r)(!1),[i,o]=Object(a.r)(void 0),l=Object(a.m)(e=>{t||2!==e.button||document.body.classList.add("no-selection")},[t]),u=Object(a.m)(e=>{t||(e.preventDefault(),document.body.classList.remove("no-selection"),i||(document.body.classList.remove("no-selection"),0===c&&document.body.classList.add("has-context-menu"),c++,s(!0),o({x:e.clientX,y:e.clientY})))},[t,i]),d=Object(a.m)(()=>{s(!1)},[]),m=Object(a.m)(()=>{o(void 0),document.body.classList.remove("no-selection"),setTimeout(()=>{c--,0===c&&document.body.classList.remove("has-context-menu")},200)},[]);return Object(a.n)(()=>{if(t||!r.k)return;const n=e.current;if(!n)return;let a;const c=()=>{a&&(clearTimeout(a),a=void 0)},l=e=>{t||r.f&&window.document.body.classList.contains("enable-symbol-menu-transforms")||(c(),a=window.setTimeout(()=>(e=>{c();const{clientX:t,clientY:a}=e.touches[0];i||(n.addEventListener("touchend",(function e(t){n.removeEventListener("touchend",e,!0),t.stopImmediatePropagation(),t.preventDefault(),t.stopPropagation()}),!0),document.body.classList.add("no-selection"),s(!0),o({x:t,y:a}))})(e),250))};return n.addEventListener("touchstart",l,{passive:!0}),n.addEventListener("touchcancel",c,!0),n.addEventListener("touchend",c,!0),n.addEventListener("touchmove",c,{passive:!0}),()=>{c(),n.removeEventListener("touchstart",l),n.removeEventListener("touchcancel",c,!0),n.removeEventListener("touchend",c,!0),n.removeEventListener("touchmove",c)}},[i,t,e]),{isContextMenuOpen:n,contextMenuPosition:i,handleBeforeContextMenu:l,handleContextMenu:u,handleContextMenuClose:d,handleContextMenuHide:m}}},function(e,t,n){"use strict";function a(e,t){return t-Math.floor(t/e)*e}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return m}));var a=n(0),r=n(2),c=n(4),s=n(5),i=n(37),o=n(68),l=n(51);function u(e,t,n){const a=e.content.text;if(!a||!a.text){const t=Object(s.N)(e);return t?[t]:void 0}const{text:r,entities:c}=a;return m(r,c,t,n)}function d(e){const t=new Set,n=[];return e.forEach((a,r)=>{if(t.has(r))return;const c=function e(t,n,a,r){const{offset:c,length:s}=t,i=new Set([n]);if(r.has(n))return;const o=a.filter((e,t)=>t>n&&e.offset>=c&&e.offsete(t,a.indexOf(t),a,r)).filter(Boolean);return o.forEach(e=>e.organizedIndexes.forEach(e=>i.add(e))),{entity:t,organizedIndexes:i,nestedEntities:o}}(a,r,e,t);c&&(c.organizedIndexes.forEach(e=>{t.add(e)}),n.push(c))}),n}function m(e,t,n,r,s){if(!t||!t.length)return h(e,n,r,s);const u=[];let m=!1;const g=d(t);function O(t,u,d,g){const v=[],{entity:j,nestedEntities:E}=d,{offset:y,length:N,type:T}=j;let C=e.substring(t,y);const M=C.length;C&&(m&&C.length>0&&"\n"===C[0]&&(C=C.substr(1),m=!1),C&&v.push(...h(C,n,r,s)));const w=t+M,I=w+N;let S=e.substring(y,y+N);const L=[];if(m&&S.length>0&&"\n"===S[0]&&(S=S.substr(1),m=!1),T===c.ApiMessageEntityTypes.Pre&&(m=!0),E.length){let e=w;E.forEach((t,n)=>{const{renderResult:a,entityEndIndex:r}=O(e,I,t,n===E.length-1);L.push(...a),e=r})}const k=s?function(e,t,n){const a="string"==typeof t&&t,r=n.length?n.join(""):Object(i.a)(t,["emoji_html","br_html"]).join("");if(!a)return r;switch(e.type){case c.ApiMessageEntityTypes.Bold:return`${r}`;case c.ApiMessageEntityTypes.Italic:return`${r}`;case c.ApiMessageEntityTypes.Underline:return`${r}`;case c.ApiMessageEntityTypes.Code:return`${r}`;case c.ApiMessageEntityTypes.Pre:return`\`\`\`
${r}
\`\`\``;case c.ApiMessageEntityTypes.Strike:return`${r}`;case c.ApiMessageEntityTypes.MentionName:return`${r}`;case c.ApiMessageEntityTypes.Url:case c.ApiMessageEntityTypes.TextUrl:return`${r}`;default:return r}}(j,S,L):function(e,t,n){const r="string"==typeof t&&t,s=n.length?n:t;if(!r)return h(s);switch(e.type){case c.ApiMessageEntityTypes.Bold:return a.a.createElement("strong",null,h(s));case c.ApiMessageEntityTypes.Blockquote:return a.a.createElement("blockquote",null,h(s));case c.ApiMessageEntityTypes.BotCommand:return a.a.createElement("a",{onClick:f,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Hashtag:case c.ApiMessageEntityTypes.Cashtag:return a.a.createElement("a",{onClick:p,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Code:return a.a.createElement("code",{className:"text-entity-code"},h(s));case c.ApiMessageEntityTypes.Email:return a.a.createElement("a",{href:"mailto:"+r,target:"_blank",rel:"noopener noreferrer",className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Italic:return a.a.createElement("em",null,h(s));case c.ApiMessageEntityTypes.MentionName:return a.a.createElement(o.a,{userId:e.userId},h(s));case c.ApiMessageEntityTypes.Mention:return a.a.createElement(o.a,{username:r},h(s));case c.ApiMessageEntityTypes.Phone:return a.a.createElement("a",{href:"tel:"+r,className:"text-entity-link"},h(s));case c.ApiMessageEntityTypes.Pre:return a.a.createElement("pre",{className:"text-entity-pre"},h(s));case c.ApiMessageEntityTypes.Strike:return a.a.createElement("del",null,h(s));case c.ApiMessageEntityTypes.TextUrl:case c.ApiMessageEntityTypes.Url:return a.a.createElement(l.a,{url:b(r,e),text:r},h(s));case c.ApiMessageEntityTypes.Underline:return a.a.createElement("ins",null,h(s));default:return h(s)}}(j,S,L);if(Array.isArray(k)?v.push(...k):v.push(k),g&&I0&&"\n"===t[0]&&(t=t.substring(1)),t&&v.push(...h(t,n,r,s))}return{renderResult:v,entityEndIndex:I}}let v=0;return g.forEach((t,n)=>{const{renderResult:a,entityEndIndex:r}=O(v,e.length,t,n===g.length-1);u.push(...a),v=r}),u}function h(e,t,n,a){if(Array.isArray(e)){const r=[];return e.forEach(e=>{r.push(...h(e,t,n,a))}),r}if(a)return Object(i.a)(e,["escape_html","emoji_html","br_html"]);const r=n?"hq_emoji":"emoji";return t?Object(i.a)(e,[r,"br","highlight"],{highlight:t}):Object(i.a)(e,[r,"br"])}function b(e,t){const{type:n,url:a}=t;return n===c.ApiMessageEntityTypes.TextUrl&&a?a:e}function f(e){Object(r.d)().sendBotCommand({command:e.currentTarget.innerText})}function p(e){Object(r.d)().setLocalTextSearchQuery({query:e.currentTarget.innerText}),Object(r.d)().searchTextMessagesLocal()}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var a=n(0),r=n(169),c=n(14),s=n(31);const i=new Map;function o(e,t=!1,n){const o=Object(a.q)(e?i.get(e):void 0),l=Object(a.q)(),u=Object(s.a)();return l.current&&t&&(clearTimeout(l.current),l.current=void 0),Object(a.n)(()=>{if(!e||o.current||t)return;const a=new Image;a.onload=()=>{const t=Object(c.f)(a);Object(r.a)(t.getContext("2d"),0,0,t.width,t.height,2,2);const n=t.toDataURL();o.current=n,u(),i.size>=1e3&&i.clear(),i.set(e,n)},n?l.current=window.setTimeout(()=>{a.src=e},n):a.src=e},[e,n,u,t]),o.current}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var a=n(0),r=n(9);function c(e,t){Object(a.n)(()=>{const t=e.current;return()=>{t&&Object(r.b)(()=>{t.pause(),t.src="",t.load()})}},t)}},,,function(e,t,n){},,,function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return i}));var a=n(1);const r=navigator.clipboard&&window.ClipboardItem,c=document.createElement("textarea");c.setAttribute("readonly",""),c.tabIndex=-1,c.className="visually-hidden";const s=e=>{c.value=e,document.body.appendChild(c);const t=document.getSelection();if(t){const e=t.rangeCount>0&&t.getRangeAt(0);c.select(),document.execCommand("copy"),e&&(t.removeAllRanges(),t.addRange(e))}document.body.removeChild(c)},i=e=>{const t=document.createElement("canvas"),n=t.getContext("2d"),a=new Image;a.onload=e=>{if(n&&e.currentTarget){const a=e.currentTarget;t.width=a.width,t.height=a.height,n.drawImage(a,0,0,a.width,a.height),t.toBlob(o,"image/png",1)}},a.src=e};async function o(e){if(e&&r)try{await navigator.clipboard.write([new window.ClipboardItem({[e.type]:e})])}catch(e){a.o&&console.error(e)}}},function(e,t,n){"use strict";var a=n(0),r=n(8),c=n(28),s=n(94),i=n(16),o=n(25);n(183);t.a=Object(a.h)(({ref:e,children:t,value:n,inputId:l,className:u,focused:d,isLoading:m,placeholder:h,disabled:b,canClose:f,onChange:p,onReset:g,onFocus:O,onBlur:v})=>{let j=Object(a.q)(null);e&&(j=e);const[E,y,N]=Object(c.a)(d);Object(a.n)(()=>{j.current&&(d?j.current.focus():j.current.blur())},[d,h]);const T=Object(s.a)();return a.a.createElement("div",{className:Object(r.a)("SearchInput",u,E&&"has-focus")},t,a.a.createElement("input",{ref:j,id:l,type:"text",placeholder:h||T("Search"),className:"form-control",value:n,disabled:b,onChange:function(e){const{currentTarget:t}=e;p(t.value)},onFocus:function(){y(),O&&O()},onBlur:function(){N(),v&&v()}}),a.a.createElement("i",{className:"icon-search"}),m&&a.a.createElement(i.a,null),!m&&(n||f)&&g&&a.a.createElement(o.a,{round:!0,size:"tiny",color:"translucent",onClick:g},a.a.createElement("span",{className:"icon-close"})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var a=n(9),r=n(55),c=n(7);function s(e,t){c.d?Object(a.b)(()=>{!function(e,t){const{scrollLeft:n,offsetWidth:a,scrollWidth:c}=e;let s=t-n;if(s<0){const e=-n;s=Math.max(s,e)}else if(s>0){const e=c-(n+a);s=Math.min(s,e)}const i=e.scrollLeft+s,o=Date.now();Object(r.a)(()=>{const t=Math.min((Date.now()-o)/450,1),n=s*(1-function(e){return 1-(1-e)**3.5}(t));return e.scrollLeft=Math.round(i-n),t<1})}(e,t)}):e.scrollTo({left:t,behavior:"smooth"})}},function(e,t,n){"use strict";var a=n(7);t.a=(e,t)=>{a.d&&(e.style.overflow="hidden"),void 0!==t&&(e.scrollTop=t),a.d&&(e.style.overflow="")}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));function a(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(37);n(193);t.a=Object(a.h)(Object(r.h)((e,{typingStatus:t})=>{if(!t.userId)return{};return{typingUser:Object(c.Db)(e,t.userId)}})(({typingStatus:e,typingUser:t})=>{const n=t&&!t.isSelf&&Object(s.X)(t);return a.a.createElement("p",{className:"typing-status"},n&&a.a.createElement("span",{className:"sender-name"},Object(i.a)(n)),e.action,a.a.createElement("span",{className:"ellipsis"}))}))},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(6),s=n(5),i=n(3),o=n(94),l=n(101),u=n(99),d=n(25);n(196);t.a=Object(a.h)(Object(r.h)((e,{chat:t})=>{const n=Object(s.kb)(t.id),a=Object(c.O)(e,t.id),r=n&&!a,i=t&&Object(s.kb)(t.id)?Object(s.X)(Object(c.Db)(e,Object(s.T)(t))):void 0;return{isPrivateChat:n,isChatWithSelf:a,isChannel:Object(s.ib)(t),isBasicGroup:Object(s.hb)(t),isSuperGroup:Object(s.mb)(t),canDeleteForAll:r,chatTitle:Object(s.l)(t),contactName:i}},(e,t)=>Object(i.l)(t,["leaveChannel","deleteHistory","deleteChannel"]))(({isOpen:e,chat:t,isChannel:n,isPrivateChat:r,isChatWithSelf:c,isBasicGroup:s,isSuperGroup:i,canDeleteForAll:m,chatTitle:h,contactName:b,onClose:f,leaveChannel:p,deleteHistory:g,deleteChannel:O})=>{const v=Object(a.m)(()=>{g({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!0}),f()},[g,t.id,t.lastMessage,f]),j=Object(a.m)(()=>{r||s?g({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!1}):!n&&!i||t.isCreator?(n||i)&&t.isCreator&&O({chatId:t.id}):p({chatId:t.id}),f()},[r,s,n,i,t.isCreator,t.lastMessage,t.id,f,g,p,O]),E=Object(o.a)();return a.a.createElement(u.a,{isOpen:e,onClose:f,className:"DeleteChatModal",header:a.a.createElement("div",{className:"modal-header"},a.a.createElement(l.a,{size:"tiny",chat:t,isSavedMessages:c}),a.a.createElement("h3",{className:"modal-title"},n&&!t.isCreator?"Leave Channel?":n&&t.isCreator?"Delete and Leave Channel?":s||i?"Leave Group?":"Delete Chat?"))},n&&!t.isCreator?a.a.createElement("p",null,"Are you sure you want to leave channel ",a.a.createElement("strong",null,h),"?"):n&&t.isCreator?a.a.createElement("p",null,"Are you sure you want to delete and leave channel ",a.a.createElement("strong",null,h),"?"):s||i?a.a.createElement("p",null,"Are you sure you want to leave group ",a.a.createElement("strong",null,h),"?"):a.a.createElement("p",null,"Are you sure you want to delete chat with ",a.a.createElement("strong",null,b),"?"),m&&a.a.createElement(d.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:v},"Delete for ",b?"me and "+b:"Everyone"),a.a.createElement(d.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:j},n&&!t.isCreator?"Leave Channel":n&&t.isCreator?"Delete and Leave Channel":s||i?"Leave Group":"Delete"+(m?" just for me":"")),a.a.createElement(d.a,{className:"confirm-dialog-button",isText:!0,onClick:f},E("Cancel")))}))},function(e,t,n){"use strict";function a(e){e.dataset.patchedForSafari||(e.addEventListener("play",()=>{const t=e.currentTime;e.addEventListener("progress",(function n(){e.buffered.length&&(e.dataset.patchForSafariInProgress="true",e.currentTime=e.duration-1,e.addEventListener("progress",()=>{delete e.dataset.patchForSafariInProgress,e.currentTime=t,e.paused&&e.play()},{once:!0}),e.removeEventListener("progress",n))}))},{once:!0}),e.dataset.patchedForSafari="true")}function r(e){return Boolean(e.dataset.patchForSafariInProgress)}n.d(t,"b",(function(){return a})),n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";var a=n(0),r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);return Object(a.o)(()=>{e(n||[])},t)}},function(e,t,n){"use strict";var a=n(0),r=n(53),c=n(5),s=n(96),i=n(111),o=n(97),l=n(167),u=n(168);t.a=Object(a.h)(({message:e,observeIntersection:t,smaller:n,uploadProgress:d,withDate:m,datetime:h,className:b,sender:f,isSelected:p,isSelectable:g,onCancelUpload:O,onDateClick:v})=>{const j=Object(a.q)(null),E=e.content.document,y=Object(r.b)(E)||"",{fileName:N,size:T,timestamp:C}=E,M=Object(s.b)(j,t),[w,I]=Object(a.r)(!1),{mediaData:S,downloadProgress:L}=Object(i.a)(Object(c.D)(e,"download"),!w),{isUploading:k,isTransferring:A,transferProgress:x}=Object(c.s)(e,d||L,w),D=Object(r.c)(E),_=D?Object(c.E)(e):void 0,R=D?E.previewBlobUrl:void 0,P=Object(o.a)(Object(c.D)(e,"pictogram"),!M),F=Object(a.m)(()=>{k?O&&O():I(e=>!e)},[k,O]),U=Object(a.m)(()=>{v(e.id,e.chatId)},[v,e.id,e.chatId]);return Object(a.n)(()=>{w&&S&&(Object(l.a)(S,N),I(!1))},[N,S,w]),a.a.createElement(u.a,{ref:j,name:N,extension:y,size:T,timestamp:m?h||C:void 0,thumbnailDataUri:_,previewData:R||P,smaller:n,isTransferring:A,isUploading:k,transferProgress:x,className:b,sender:f,isSelectable:g,isSelected:p,onClick:F,onDateClick:v?U:void 0})})},function(e,t,n){"use strict";var a=n(0),r=n(12),c=n(17);t.a=e=>{const{isOpen:t}=e,n=Object(c.a)(r.a.Extra,"StickerSetModal",!t);return n?a.a.createElement(n,e):void 0}},function(e,t,n){"use strict";var a=n(0),r=n(1),c=n(8),s=n(42),i=n(29),o=n(69),l=n(28),u=n(94),d=n(25);n(228);const m={B:"bold",STRONG:"bold",I:"italic",EM:"italic",U:"underline",DEL:"strikethrough",CODE:"monospace"};t.a=Object(a.h)(({isOpen:e,anchorPosition:t,selectedRange:n,onClose:h})=>{const b=Object(a.q)(null),f=Object(a.q)(null),{shouldRender:p,transitionClassNames:g}=Object(i.a)(e),[O,v,j]=Object(l.a)(),[E,y]=Object(a.r)(""),[N,T]=Object(a.r)(!1),[C,M]=Object(a.r)(),[w,I]=Object(a.r)({});Object(a.n)(()=>e?Object(s.a)(h):void 0,[e,h]),Object(o.a)(e,b,h),Object(a.n)(()=>{O?f.current.focus():(y(""),T(!1))},[O]),Object(a.n)(()=>{p||(j(),I({}),M(void 0))},[j,p]),Object(a.n)(()=>{if(!e||!n)return;const t={};let{parentElement:a}=n.commonAncestorContainer;for(;a&&a.id!==r.u;){const e=m[a.tagName];e&&(t[e]=!0),a=a.parentElement}I(t)},[e,n,v]);const S=Object(a.m)(()=>{if(n)return n.toString()},[n]),L=Object(a.m)(()=>{if(n)return n.commonAncestorContainer.parentElement},[n]);function k(){const e=f.current;if(!e)return;const{offsetWidth:t,scrollWidth:n,scrollLeft:a}=e;if(n<=t)return void M(void 0);let r="";a0&&(r+=" mask-left"),M(r)}function A(e){if(w[e])return"active";if("monospace"===e||"strikethrough"===e){if(Object.keys(w).some(t=>t!==e&&!!w[t]))return"disabled"}else if(w.monospace||w.strikethrough)return"disabled"}const x=Object(a.m)(()=>{I(e=>(document.execCommand(e.bold?"removeFormat":"bold"),Object.keys(e).forEach(t=>{"italic"!==t&&"underline"!==t||!e[t]||document.execCommand(t)}),{...e,bold:!e.bold}))},[]),D=Object(a.m)(()=>{document.execCommand("italic"),I(e=>({...e,italic:!e.italic}))},[]),_=Object(a.m)(()=>{document.execCommand("underline"),I(e=>({...e,underline:!e.underline}))},[]),R=Object(a.m)(()=>{if(w.strikethrough){const e=L();if(!n||!e||"DEL"!==e.tagName||!e.textContent)return;return e.replaceWith(e.textContent),void I(e=>({...e,strikethrough:!1}))}const e=S();document.execCommand("insertHTML",!1,`${e}`),h()},[L,S,h,n,w.strikethrough]),P=Object(a.m)(()=>{if(w.monospace){const e=L();if(!n||!e||"CODE"!==e.tagName||!e.textContent)return;return e.replaceWith(e.textContent),void I(e=>({...e,monospace:!1}))}const e=S();document.execCommand("insertHTML",!1,`${e}`),h()},[L,S,h,n,w.monospace]);function F(){const e=E.includes("://")?E:"http://"+E;if(N){const t=L();if(!t||"A"!==t.tagName)return;return t.href=e,void h()}const t=S();!function(){if(!n)return;const e=window.getSelection();e&&(e.removeAllRanges(),e.addRange(n))}(),document.execCommand("insertHTML",!1,`${t}`),h()}const U=Object(a.m)(e=>{const t={KeyK:v,KeyB:x,KeyU:_,KeyI:D,KeyM:P,KeyS:R}[e.code];!e.altKey&&(e.ctrlKey||e.metaKey)&&t&&(e.preventDefault(),e.stopPropagation(),t())},[x,D,_,P,R,v]);Object(a.n)(()=>(e&&document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)),[e,U]);const B=Object(u.a)();if(!p)return;const q=Object(c.a)("TextFormatter",g,O&&"link-control-shown"),H=Object(c.a)("TextFormatter-link-url-confirm",!!E.length&&"shown"),$=t?`left: ${t.x}px; top: ${t.y}px;--text-formatter-left: ${t.x}px;`:"";return a.a.createElement("div",{ref:b,className:q,style:$,onKeyDown:function(e){"Enter"===e.key&&O&&(F(),e.preventDefault())}},a.a.createElement("div",{className:"TextFormatter-buttons"},a.a.createElement(d.a,{color:"translucent",ariaLabel:"Bold text",className:A("bold"),onClick:x},a.a.createElement("i",{className:"icon-bold"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Italic text",className:A("italic"),onClick:D},a.a.createElement("i",{className:"icon-italic"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Underlined text",className:A("underline"),onClick:_},a.a.createElement("i",{className:"icon-underlined"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Strikethrough text",className:A("strikethrough"),onClick:R},a.a.createElement("i",{className:"icon-strikethrough"})),a.a.createElement(d.a,{color:"translucent",ariaLabel:"Monospace text",className:A("monospace"),onClick:P},a.a.createElement("i",{className:"icon-monospace"})),a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement(d.a,{color:"translucent",ariaLabel:B("TextFormat.AddLinkTitle"),onClick:v},a.a.createElement("i",{className:"icon-link"}))),a.a.createElement("div",{className:"TextFormatter-link-control"},a.a.createElement("div",{className:"TextFormatter-buttons"},a.a.createElement(d.a,{color:"translucent",ariaLabel:B("Cancel"),onClick:j},a.a.createElement("i",{className:"icon-arrow-left"})),a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement("div",{className:Object(c.a)("TextFormatter-link-url-input-wrapper",C)},a.a.createElement("input",{ref:f,className:"TextFormatter-link-url-input",type:"text",value:E,placeholder:"Enter URL...",autoComplete:"off",inputMode:"url",onChange:function(e){y(e.target.value),k()},onScroll:k})),a.a.createElement("div",{className:H},a.a.createElement("div",{className:"TextFormatter-divider"}),a.a.createElement(d.a,{color:"translucent",ariaLabel:B("Save"),className:"color-primary",onClick:F},a.a.createElement("i",{className:"icon-check"}))))))})},function(e,t,n){"use strict";var a=n(0),r=n(30),c=n(5),s=n(97),i=n(104);n(236);t.a=Object(a.h)(({message:e,idPrefix:t="shared-media",onClick:n})=>{const o=Object(a.m)(()=>{n(e.id,e.chatId)},[e.id,e.chatId,n]),l=Object(c.E)(e),u=Object(s.a)(Object(c.D)(e,"pictogram")),{shouldRenderThumb:d,shouldRenderFullMedia:m,transitionClassNames:h}=Object(i.a)(u,"slow"),b=Object(c.O)(e);return a.a.createElement("div",{id:`${t}${e.id}`,className:"Media scroll-item",onClick:n?o:void 0},d&&a.a.createElement("img",{src:l,alt:""}),m&&a.a.createElement("img",{src:u,className:h+" full-media",alt:""}),b&&a.a.createElement("span",{className:"video-duration"},b.isGif?"GIF":Object(r.e)(b.duration)))})},,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(7),s=n(30),i=n(5);var o=n(8),l=n(37);var u=n(111),d=n(29),m=n(125),h=n(165),b=n(94),f=n(25),p=n(112),g=n(110);n(210);const O=c.f?20:25,v=c.f?50:75;function j(e,t,{handleStartSeek:n,handleSeek:r,handleStopSeek:c}){return a.a.createElement("div",{className:"seekline no-selection",onMouseDown:n,onMouseMove:r,onMouseUp:c},a.a.createElement("span",{className:"seekline-buffered-progress"},a.a.createElement("i",{style:`transform: translateX(${100*t}%)`})),a.a.createElement("span",{className:"seekline-play-progress"},a.a.createElement("i",{style:`transform: translateX(${100*e}%)`})),a.a.createElement("span",{className:"seekline-thumb"},a.a.createElement("i",{style:`transform: translateX(${100*e}%)`})))}t.a=Object(a.h)(Object(r.h)(e=>({theme:e.settings.byKey.theme}))(({theme:e,message:t,senderTitle:n,uploadProgress:r,renderingFor:E,date:y,lastSyncTime:N,className:T,isSelectable:C,isSelected:M,onPlay:w,onReadMedia:I,onCancelUpload:S,onDateClick:L})=>{const{content:{audio:k,voice:A},isMediaUnread:x}=t,D=Boolean(A),_=Object(a.q)(!1),[R,P]=Object(a.r)(!1),F=N,{mediaData:U,downloadProgress:B}=Object(u.a)(Object(i.D)(t,"inline"),!F,Object(i.C)(t,"inline"));const{isBuffered:q,bufferedProgress:H,bufferingHandlers:$,checkBuffering:Y}=Object(m.a)(),{isPlaying:V,playProgress:K,playPause:z,setCurrentTime:W,duration:X}=Object(h.a)(Object(i.A)(t),Object(i.r)(t),U,$,Y,R,(function(){P(!0),w(t.id,t.chatId)}),Object(i.rb)(t));Object(a.n)(()=>{P(V)},[V]);const{isUploading:G,isTransferring:Q,transferProgress:J}=Object(i.s)(t,r||B,R&&!q),{shouldRender:Z,transitionClassNames:ee}=Object(d.a)(Q),te=Object(a.m)(()=>{G?S&&S():(V||w(t.id,t.chatId),P(!R),z())},[V,G,t.id,t.chatId,S,w,z,R]);Object(a.n)(()=>{V&&I&&x&&I()},[V,x,I]);const ne=Object(a.m)(e=>{if(_.current){const t=e.currentTarget.closest(".seekline,.waveform");if(t){const{width:n,left:a}=t.getBoundingClientRect();W(X*((e.clientX-a)/n))}}},[X,W]),ae=Object(a.m)(e=>{_.current=!0,ne(e)},[ne]),re=Object(a.m)(()=>{_.current=!1},[]),ce=Object(a.m)(()=>{L(t.id,t.chatId)},[L,t.id,t.chatId]);Object(b.a)();const se={handleStartSeek:ae,handleSeek:ne,handleStopSeek:re},ie=Object(i.sb)(t),oe=Object(a.p)(()=>A&&function(e,t=0,n=!1,{handleStartSeek:r,handleSeek:c,handleStopSeek:s},i){const{waveform:o,duration:l}=e;if(!o)return;const u="dark"===i?"#494B75":"#CBCBCB",d="dark"===i?"#C69C85":"#B0DEA6",m="dark"===i?"#868DF5":"#54a3e6",h="dark"===i?"#FFFFFF":"#53ad53",b=Math.min(l/30,1),f=Math.round(O+(v-O)*b),p=function(e){const t=8*e.length,n=Math.floor(t/5);if(!n)return[];const a=Array(n),r=e;for(let e=0,t=n-1;e!==t;++e){const t=Math.floor(5*e/8),n=Math.floor(5*e%8),c=r[t]+(r[t+1]<<8);a[e]=c>>n&31}const c=Math.floor(5*(n-1)/8),s=Math.floor(5*(n-1)%8),i=r[c]+(r[c+1]<<8);return a[n-1]=i>>s&31,a}(new Uint8Array(o)),{data:g,peak:j}=function(e,t){let n=0;const a=new Array(t),r=e.length/t,c=e[0],s=e[e.length-1];for(let u=0;u{i.globalAlpha=s/e.length>=t?.5:1,i.fillStyle=t>s/e.length?r:a;const o=Math.max(2,c/Math.max(1,n)*23);!function(e,t,n,a,r,c){a<2*c&&(c=a/2);r<2*c&&(c=r/2);e.beginPath(),e.moveTo(t+c,n),e.arcTo(t+a,n,t+a,n-r,c),e.arcTo(t+a,n-r,t,n-r,c),e.arcTo(t,n-r,t,n,c),e.arcTo(t,n,t+a,n,c),e.closePath()}(i,4*s,23,2,o,1),i.fill()}),{src:s.toDataURL(),width:c,height:23}}(g,t,{peak:j,fillStyle:n?d:u,progressFillStyle:n?h:m});return a.a.createElement("img",{src:E,alt:"",width:y,height:N,className:"waveform",draggable:!1,onMouseDown:r,onMouseMove:c,onMouseUp:s})}(A,K,ie,se,e),[A,K,ie,se,e]),le=Object(o.a)("Audio media-inner",T,ie&&!E&&"own",E&&"bigger",M&&"audio-is-selected"),ue=["toggle-play"];Z?ue.push("loading"):V?ue.push("pause"):V||ue.push("play");const de=V||K>0&&K<1,me=Object(o.a)("content",de&&"with-seekline");return a.a.createElement("div",{className:le},C&&a.a.createElement("div",{className:"message-select-control"},M&&a.a.createElement("i",{className:"icon-select"})),a.a.createElement(f.a,{round:!0,ripple:!c.f,size:E?"smaller":"tiny",className:ue.join(" "),ariaLabel:V?"Pause audio":"Play audio",onClick:te},a.a.createElement("i",{className:"icon-play"}),a.a.createElement("i",{className:"icon-pause"})),Z&&a.a.createElement("div",{className:Object(o.a)("media-loading",ee)},a.a.createElement(p.a,{progress:J,transparent:!0,size:E?"m":"s",onClick:te})),"searchResult"===E&&a.a.createElement(a.a.Fragment,null,a.a.createElement("div",{className:me},a.a.createElement("div",{className:"content-row"},a.a.createElement("p",{className:"title"},Object(l.a)(function(){if(D)return n||"Voice";const{title:e,fileName:t}=k;return e||t}())),a.a.createElement("div",{className:"message-date"},y&&a.a.createElement(g.a,{className:"date",onClick:ce},Object(s.g)(1e3*y)))),de&&j(K,H,se),!de&&a.a.createElement("p",{className:"duration"},K>0?Object(s.e)(X*K)+" / ":void 0,function(){if(D)return Object(s.e)(A.duration);const{performer:e}=k;return a.a.createElement(a.a.Fragment,null,e&&Object(l.a)(e),e&&n&&a.a.createElement("span",null,"•"),n&&Object(l.a)(n))}()))),"searchResult"!==E&&k&&function(e,t,n,r,c,i,o){const{title:u,performer:d,duration:m,fileName:h}=e,b=t||n>0&&n<1;return a.a.createElement("div",{className:"content"},a.a.createElement("p",{className:"title"},Object(l.a)(u||h)),b&&j(n,r,c),!b&&a.a.createElement("div",{className:"meta"},a.a.createElement("span",{className:"performer"},Object(l.a)(d||"Unknown")),i&&a.a.createElement(a.a.Fragment,null," ","•"," ",a.a.createElement(g.a,{className:"date",onClick:o},Object(s.d)(1e3*i)))),a.a.createElement("p",{className:"duration"},n>0?Object(s.e)(m*n)+" / ":void 0,Object(s.e)(m)))}(k,V,K,H,se,y,L?ce:void 0),"searchResult"!==E&&A&&function(e,t,n){return a.a.createElement("div",{className:"content"},t,a.a.createElement("p",{className:"voice-duration"},Object(s.e)(e.duration),n&&a.a.createElement("span",null,"•")))}(A,oe,x))}))},function(e,t,n){"use strict";var a=n(0),r=n(145),c=n(38),s=n(131),i=n(94),o=n(8);n(189);var l=Object(a.h)(({className:e,title:t,active:n,badgeCount:r,isBadgeActive:c,previousActiveTab:s,onClick:i,clickArg:l})=>{const u=Object(a.q)(null);return Object(a.o)(()=>{if(!n||void 0===s)return;const e=u.current,t=e.querySelector("i"),a=e.parentElement.children[s].querySelector("i");a.classList.remove("animate"),t.classList.remove("animate");const r=a.parentElement.offsetLeft-t.parentElement.offsetLeft,c=a.clientWidth/t.clientWidth;t.style.transform=`translate3d(${r}px, 0, 0) scale3d(${c}, 1, 1)`,requestAnimationFrame(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{t.classList.add("animate"),t.style.transform="none"})})})},[n,s]),a.a.createElement("button",{type:"button",className:Object(o.a)("Tab",e,n&&"active"),onClick:()=>i(l),ref:u},a.a.createElement("span",null,t,!!r&&a.a.createElement("span",{className:Object(o.a)("badge",c&&"active")},r),a.a.createElement("i",null)))});n(190);t.a=Object(a.h)(({tabs:e,activeTab:t,onSwitchTab:n})=>{const o=Object(a.q)(null),u=Object(c.a)(t);Object(s.a)(o),Object(a.n)(()=>{const e=o.current;if(e.scrollWidth<=e.offsetWidth)return;const t=e.querySelector(".Tab.active");if(t){const n=t.offsetLeft-e.offsetWidth/2+t.offsetWidth/2;if(Math.abs(n-e.scrollLeft)<16)return;Object(r.a)(e,n)}},[t]);const d=Object(i.a)();return a.a.createElement("div",{className:"TabList no-selection no-scrollbar",ref:o},e.map((e,r)=>a.a.createElement(l,{key:e.title,title:d(e.title),active:r===t,badgeCount:e.badgeCount,isBadgeActive:e.isBadgeActive,previousActiveTab:u,onClick:n,clickArg:r})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const a={CHAT_RESTRICTED:"You can't send messages in this chat, you were restricted",CHAT_WRITE_FORBIDDEN:"You can't write in this chat",CHAT_SEND_POLL_FORBIDDEN:"You can't create polls in this chat",CHAT_SEND_STICKERS_FORBIDDEN:"You can't send stickers in this chat",CHAT_SEND_GIFS_FORBIDDEN:"You can't send gifs in this chat",CHAT_SEND_MEDIA_FORBIDDEN:"You can't send media in this chat",CHAT_LINK_EXISTS:"The chat is public, you can't hide the history to new users",SLOWMODE_WAIT_X:"Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.",USER_BANNED_IN_CHANNEL:"You're banned from sending messages in supergroups / channels",USER_IS_BLOCKED:"You were blocked by this user",YOU_BLOCKED_USER:"You blocked this user",IMAGE_PROCESS_FAILED:"Failure while processing image",MEDIA_EMPTY:"The provided media object is invalid",MEDIA_INVALID:"Media invalid",PHOTO_EXT_INVALID:"The extension of the photo is invalid",PHOTO_INVALID_DIMENSIONS:"The photo dimensions are invalid",PHOTO_SAVE_FILE_INVALID:"Internal issues, try again later",MESSAGE_DELETE_FORBIDDEN:"You can't delete one of the messages you tried to delete, most likely because it is a service message.",MESSAGE_POLL_CLOSED:"Poll closed",MESSAGE_EDIT_TIME_EXPIRED:"You can't edit this message anymore.",CHAT_ADMIN_REQUIRED:"You must be an admin in this chat to do this",PINNED_DIALOGS_TOO_MUCH:"Sorry, you can only pin 5 chats to the top",DIALOG_FILTERS_TOO_MUCH:"Sorry, you can't have more than 10 folders",CHANNEL_PRIVATE:"This channel is private",MEDIA_CAPTION_TOO_LONG:"The provided caption is too long",ADDRESS_STREET_LINE1_INVALID:"The address you provided is not valid",ADDRESS_STREET_LINE2_INVALID:"The address you provided is not valid",ADDRESS_CITY_INVALID:"The city you provided is not valid",ADDRESS_COUNTRY_INVALID:"The country you provided is not valid",ADDRESS_POSTCODE_INVALID:"The postcode you provided is not valid",ADDRESS_STATE_INVALID:"The state you provided is not valid",REQ_INFO_NAME_INVALID:"The name you provided is not valid",REQ_INFO_PHONE_INVALID:"The phone you provided is not valid",REQ_INFO_EMAIL_INVALID:"The email you provided is not valid",LINK_NOT_MODIFIED:"This discussion is already linked to the channel",SERVICE_WORKER_DISABLED:"Service Worker is disabled. Please reload the page without holding key.",CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS:"The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.",FRESH_RESET_AUTHORISATION_FORBIDDEN:"You can’t logout other sessions if less than 24 hours have passed since you logged on the current session",BOTS_TOO_MUCH:"There are too many bots in this chat/channel",BOT_GROUPS_BLOCKED:"This bot can't be added to groups",USERS_TOO_MUCH:"The maximum number of users has been exceeded",USER_CHANNELS_TOO_MUCH:"One of the users you tried to add is already in too many channels/supergroups",USER_KICKED:"This user was kicked from this supergroup/channel",USER_NOT_MUTUAL_CONTACT:"The provided user is not a mutual contact",USER_PRIVACY_RESTRICTED:"The user's privacy settings do not allow you to do this",INVITE_HASH_EMPTY:"The invite hash is empty",INVITE_HASH_EXPIRED:"The invite link has expired",INVITE_HASH_INVALID:"The invite hash is invalid",CHANNELS_TOO_MUCH:"You have joined too many channels/supergroups",USER_ALREADY_PARTICIPANT:"You already in the group"};function r(e){const{message:t,isSlowMode:n,textParams:r}=e;if(n){const e=t.indexOf(" (caused by");return e>0?t.substring(0,e):t}let c=a[t];return c&&r&&(c=Object.keys(r).reduce((e,t)=>e.replace(t,r[t]),c)),c}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(5);t.a=({chat:e,privateChatUser:t,handleDelete:n,folderId:s,isPinned:i})=>{const{toggleChatPinned:o,updateChatMutedState:l,toggleChatArchived:u,toggleChatUnread:d}=Object(r.d)();return Object(a.p)(()=>{if(!e)return;const a=t&&t.isSelf,r=e.unreadCount||e.hasUnreadMark?{title:"Mark as Read",icon:"readchats",handler:()=>d({id:e.id})}:{title:"Mark as Unread",icon:"unread",handler:()=>d({id:e.id})},m=i?{title:"Unpin",icon:"unpin",handler:()=>o({id:e.id,folderId:s})}:{title:"Pin",icon:"pin",handler:()=>o({id:e.id,folderId:s})},h=e.isMuted?{title:"Unmute",icon:"unmute",handler:()=>l({chatId:e.id,isMuted:!1})}:{title:"Mute",icon:"mute",handler:()=>l({chatId:e.id,isMuted:!0})},b=Object(c.gb)(e)?{title:"Unarchive",icon:"unarchive",handler:()=>u({id:e.id})}:{title:"Archive",icon:"archive",handler:()=>u({id:e.id})};return[r,m,...a?[]:[h,b],{title:Object(c.kb)(e.id)?"Delete":Object(c.d)(e)?"Delete and Leave":"Leave",icon:"delete",destructive:!0,handler:n}]},[e,t,n,s,i,o,l,u,d])}},function(e,t,n){"use strict";var a=n(0),r=n(30),c=n(162);n(195);t.a=({message:e,outgoingStatus:t})=>a.a.createElement("div",{className:"LastMessageMeta"},t&&a.a.createElement(c.a,{status:t}),a.a.createElement("span",{className:"time"},Object(r.g)(1e3*e.date)))},function(e,t,n){"use strict";var a,r=n(0),c=n(100);n(194);!function(e){e[e.failed=0]="failed",e[e.pending=1]="pending",e[e.succeeded=2]="succeeded",e[e.read=3]="read"}(a||(a={}));t.a=({status:e})=>r.a.createElement("div",{className:"MessageOutgoingStatus"},r.a.createElement(c.a,{name:"reveal",activeKey:a[e]},()=>r.a.createElement("i",{className:"icon-message-"+e})))},function(e,t,n){"use strict";var a=n(0);t.a=(e,t,n,r,c=0,s=0)=>{const[i,o]=Object(a.r)("right"),[l,u]=Object(a.r)("bottom"),[d,m]=Object(a.r)("");return Object(a.n)(()=>{const a=t();if(!e||!a)return;let{x:i,y:l}=e;const d={width:0,left:0,height:0,top:0},h=r(),b=n(),f=a.getBoundingClientRect(),p=h?{width:h.offsetWidth,height:h.offsetHeight}:d,g=b?b.getBoundingClientRect():d;i+p.width+c0?(o("right"),i-=3):(o("left"),i=16),l+p.height{const{shouldRender:u,transitionClassNames:d}=Object(r.a)(e,void 0,void 0,!t&&void 0),m=Object(c.a)(e),h=Object(c.a)(l),b=Object(a.q)();return m&&!e&&(b.current=h),u&&a.a.createElement("div",{id:n,className:Object(s.a)(i,d),onClick:o},e?l():b.current())}},function(e,t,n){"use strict";var a=n(0),r=n(166),c=n(52),s=n(150),i=n(103);t.a=(e,t,n,o,l,u=!1,d,m=!1)=>{const h=Object(a.q)(null),[b,f]=Object(a.r)(!1);let p=b;const[g,O]=Object(a.r)(0);Object(i.a)(()=>{h.current=Object(r.a)(e,(e,n)=>{switch(e){case"onPlay":f(!0);break;case"onPause":f(!1);break;case"onTimeUpdate":{const{proxy:e}=h.current,n=e.duration&&Number.isFinite(e.duration)?e.duration:t;O(e.currentTime/n);break}}o&&o[e]&&o[e](n)},d);const{proxy:n}=h.current;b||n.paused||(f(!0),p=!0),l&&l(n)},[e]);const{play:v,pause:j,setCurrentTime:E,proxy:y,destroy:N}=h.current,T=y.duration&&Number.isFinite(y.duration)?y.duration:t;Object(a.n)(()=>{T&&!Object(s.a)(y)&&O(y.currentTime/T)},[T,g,y]),Object(a.n)(()=>()=>{N(m)},[N,m]),Object(c.a)(([e,t])=>{e===u&&n===t||y.src&&y.paused||u&&n&&!b&&v(n)},[u,n,b,v,y.src,y.paused]);const C=Object(a.m)(()=>{b?j():n&&v(n)},[n,j,v,b]);return{isPlaying:p,playProgress:g,playPause:C,setCurrentTime:E,audioProxy:y,duration:T}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return m}));var a=n(7),r=n(124),c=n(150),s=n(2),i=n(5);const o=new Map;let l,u=[];function d(){const e=l&&o.get(l);e&&e.audio.pause()}function m(e,t,n){o.has(e)||(o.set(e,function(e,t){const n=new Audio;function a(t){return a=>{o.has(e)&&(Object(c.a)(n)||o.get(e).handlers.forEach(e=>{e(t,a)}))}}return n.addEventListener("timeupdate",a("onTimeUpdate")),n.addEventListener("play",a("onPlay")),n.addEventListener("pause",a("onPause")),n.addEventListener("loadstart",a("onLoadStart")),n.addEventListener("loadeddata",a("onLoadedData")),n.addEventListener("playing",a("onPlaying")),n.addEventListener("ended",()=>{if(Object(c.a)(n))return;const t=u[u.indexOf(e)+1];if(!t)return;if(!o.has(t))return void Object(s.d)().openAudioPlayer(Object(i.yb)(t));const a=o.get(t);a.onForcePlay&&a.onForcePlay(),l=t,a.audio.src&&Object(r.a)(a.audio)}),{audio:n,proxy:new Proxy(n,{get:(e,t)=>e[t]}),handlers:[],onForcePlay:t}}(e,n)),u.includes(e)||u.push(e));const{audio:d,proxy:m,handlers:h}=o.get(e);return h.push(t),{play(t){l&&l!==e&&o.get(l).audio.pause(),l=e,d.src||(d.src=t,d.preload="auto",t.includes("/progressive/")&&a.i&&Object(c.b)(d)),Object(r.a)(d)},pause(){l===e&&d.pause()},setCurrentTime(t){l===e&&(d.currentTime=t)},proxy:m,destroy(n=!1){const a=o.get(e);a&&(a.handlers=a.handlers.filter(e=>e!==t),a.handlers.length||(a.audio.pause(),o.delete(e),n&&(u=u.filter(t=>t!==e)),e===l&&(l=void 0)))}}}},function(e,t,n){"use strict";function a(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.click()}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a=n(0),r=n(29),c=n(104),s=n(8),i=n(30),o=n(53),l=n(105),u=n(37),d=n(112),m=n(110);n(209);t.a=Object(a.h)(({ref:e,name:t,size:n,extension:h="",timestamp:b,sender:f,thumbnailDataUri:p,previewData:g,className:O,smaller:v,isTransferring:j,isUploading:E,isSelectable:y,isSelected:N,transferProgress:T,onClick:C,onDateClick:M})=>{let w=Object(a.q)(null);e&&(w=e);const{shouldRender:I,transitionClassNames:S}=Object(r.a)(j,void 0,!0),L=Object(o.a)(h),k=Object(o.e)(n),{shouldRenderThumb:A,shouldRenderFullMedia:x,transitionClassNames:D}=Object(c.a)(g,"slow"),{width:_,height:R}=Object(l.i)(v),P=Object(s.a)("File",O,v&&"smaller",C&&!E&&"interactive",N&&"file-is-selected");return a.a.createElement("div",{ref:w,className:P},y&&a.a.createElement("div",{className:"message-select-control"},N&&a.a.createElement("i",{className:"icon-select"})),a.a.createElement("div",{className:"file-icon-container",onClick:E?void 0:C},p||g?a.a.createElement("div",{className:"file-preview media-inner"},A&&a.a.createElement("img",{src:p,width:_,height:R,className:"thumbnail",alt:""}),x&&a.a.createElement("img",{src:g,className:"full-media "+D,width:_,height:R,alt:""})):a.a.createElement("div",{className:"file-icon "+L},h.length<=4&&a.a.createElement("span",{className:"file-ext"},h)),I&&a.a.createElement("div",{className:Object(s.a)("file-progress",L,S)},a.a.createElement(d.a,{progress:T,size:v?"s":"m",onClick:E?C:void 0})),C&&a.a.createElement("i",{className:Object(s.a)("icon-download",I&&"hidden")})),a.a.createElement("div",{className:"file-info"},a.a.createElement("div",{className:"file-title"},Object(u.a)(t)),a.a.createElement("div",{className:"file-subtitle"},a.a.createElement("span",null,j&&T?Math.round(100*T)+"%":k),f&&a.a.createElement("span",{className:"file-sender"},Object(u.a)(f)),!f&&b&&a.a.createElement(a.a.Fragment,null," ",a.a.createElement(m.a,{onClick:M},Object(i.d)(1e3*b))))),f&&b&&a.a.createElement(m.a,{onClick:M},Object(i.g)(1e3*b)))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));const a=[1,57,41,21,203,34,97,73,227,91,149,62,105,45,39,137,241,107,3,173,39,71,65,238,219,101,187,87,81,151,141,133,249,117,221,209,197,187,177,169,5,153,73,139,133,127,243,233,223,107,103,99,191,23,177,171,165,159,77,149,9,139,135,131,253,245,119,231,224,109,211,103,25,195,189,23,45,175,171,83,81,79,155,151,147,9,141,137,67,131,129,251,123,30,235,115,113,221,217,53,13,51,50,49,193,189,185,91,179,175,43,169,83,163,5,79,155,19,75,147,145,143,35,69,17,67,33,65,255,251,247,243,239,59,29,229,113,111,219,27,213,105,207,51,201,199,49,193,191,47,93,183,181,179,11,87,43,85,167,165,163,161,159,157,155,77,19,75,37,73,145,143,141,35,138,137,135,67,33,131,129,255,63,250,247,61,121,239,237,117,29,229,227,225,111,55,109,216,213,211,209,207,205,203,201,199,197,195,193,48,190,47,93,185,183,181,179,178,176,175,173,171,85,21,167,165,41,163,161,5,79,157,78,154,153,19,75,149,74,147,73,144,143,71,141,140,139,137,17,135,134,133,66,131,65,129,1],r=[0,9,10,10,14,12,14,14,16,15,16,15,16,15,15,17,18,17,12,18,16,17,17,19,19,18,19,18,18,19,19,19,20,19,20,20,20,20,20,20,15,20,19,20,20,20,21,21,21,20,20,20,21,18,21,21,21,21,20,21,17,21,21,21,22,22,21,22,22,21,22,21,19,22,22,19,20,22,22,21,21,21,22,22,22,18,22,22,21,22,22,23,22,20,23,22,22,23,23,21,19,21,21,21,23,23,23,22,23,23,21,23,22,23,18,22,23,20,22,23,23,23,21,22,20,22,21,22,24,24,24,24,24,22,21,24,23,23,24,21,24,23,24,22,24,24,22,24,24,22,23,24,24,24,20,23,22,23,24,24,24,24,24,24,24,23,21,23,22,23,24,24,24,22,24,24,24,23,22,24,24,25,23,25,25,23,24,25,25,24,22,25,25,25,24,23,24,25,25,25,25,25,25,25,25,25,25,25,25,23,25,23,24,25,25,25,25,25,25,25,25,25,24,22,25,25,23,25,25,20,24,25,24,25,25,22,24,25,24,25,24,25,25,24,25,25,25,25,22,25,25,25,24,25,24,25,18];function c(e,t,n,c,s,i,o){if(Number.isNaN(i)||i<1)return;i|=0,Number.isNaN(o)&&(o=1),(o|=0)>3&&(o=3),o<1&&(o=1);const l=e.getImageData(t,n,c,s),u=l.data;let d,m,h,b,f,p,g,O,v,j,E,y,N=c-1,T=s-1,C=i+1,M=[],w=[],I=[],S=a[i],L=r[i],k=[],A=[];for(;o-- >0;){for(y=E=0,f=0;fN?N:p)<<2),d+=u[g++],m+=u[g++],h+=u[g++];for(b=0;b0?g<<2:0),O=y+k[b],v=y+A[b],d+=u[O++]-u[v++],m+=u[O++]-u[v++],h+=u[O++]-u[v++],E++;y+=c<<2}for(b=0;bT?0:c,d+=M[j],m+=w[j],h+=I[j];for(E=b<<2,f=0;f>>L,u[E+1]=m*S>>>L,u[E+2]=h*S>>>L,0==b&&(k[f]=((g=f+C)0?g*c:0),O=b+k[f],v=b+A[f],d+=M[O]-M[v],m+=w[O]-w[v],h+=I[O]-I[v],E+=c<<2}}e.putImageData(l,t,n)}},function(e,t,n){"use strict";var a=n(0),r=n(1),c=n(29),s=n(8),i=n(42),o=n(113);n(216);t.a=Object(a.h)(({message:e,duration:t=3e3,onDismiss:n})=>{const[l,u]=Object(a.r)(!0),d=Object(a.q)(null),{transitionClassNames:m}=Object(c.a)(l),h=Object(a.m)(()=>{u(!1),setTimeout(n,150+r.c)},[n]);Object(a.n)(()=>l?Object(i.a)(h):void 0,[l,h]),Object(a.n)(()=>(d.current=window.setTimeout(h,t),()=>{d.current&&(clearTimeout(d.current),d.current=void 0)}),[t,h]);const b=Object(a.m)(()=>{d.current&&(clearTimeout(d.current),d.current=void 0)},[]),f=Object(a.m)(()=>{d.current=window.setTimeout(h,t)},[t,h]);return a.a.createElement(o.a,{className:"Notification-container",containerId:"#middle-column-portals"},a.a.createElement("div",{className:Object(s.a)("Notification",m),onClick:h,onMouseEnter:b,onMouseLeave:f},a.a.createElement("div",{className:"content"},e)))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var a=n(1);function r(e){const{commonAncestorContainer:t}=e;let n=t,r=1;for(;n&&n.id!==a.u&&r<5;)n=n.parentElement,r++;return Boolean(n&&n.id===a.u)}},function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(1),s=n(6),i=n(9),o=n(126),l=n(8),u=n(3),d=n(7),m=n(50),h=n(151),b=n(28),f=n(58),p=n(171),g=n(154);const O=d.f?256:416;t.a=Object(a.h)(Object(r.h)(e=>{const{chatId:t,threadId:n}=Object(s.y)(e)||{},{messageSendKeyCombo:a}=e.settings.byKey;return{currentChatId:t,messageSendKeyCombo:a,replyingToId:t&&n?Object(s.jb)(e,t,n):void 0,noTabCapture:e.isPollModalOpen||e.payment.isPaymentModalOpen}},(e,t)=>Object(u.l)(t,["editLastMessage"]))(({id:e,editableInputId:t,html:n,placeholder:r,shouldSetFocus:s,shouldSupressFocus:u,onUpdate:v,onSupressedFocus:j,onSend:E,currentChatId:y,replyingToId:N,noTabCapture:T,messageSendKeyCombo:C,editLastMessage:M})=>{const w=Object(a.q)(null),I=Object(a.q)(null),S=Object(a.q)(!1),[L,k,A]=Object(b.a)(),[x,D]=Object(a.r)(),[_,R]=Object(a.r)();Object(h.a)(([e])=>{n!==w.current.innerHTML&&(w.current.innerHTML=n),n!==I.current.innerHTML&&(I.current.innerHTML=n),void 0!==e&&e!==n&&function(e=!1){const t=w.current,n=I.current,a=Number(t.style.height.replace("px","")),r=Math.min(n.scrollHeight,O);if(r===a)return;const c=Math.round(50*Math.log(Math.abs(r-a))),s=()=>{t.style.height=r+"px",t.style.transitionDuration=c+"ms",t.classList.toggle("overflown",n.scrollHeight>O)};e?requestAnimationFrame(s):s()}(!n.length)},[n]);const P=Object(a.m)(()=>{w.current.closest(".from, .to")?setTimeout(P,350):Object(o.a)(w.current)},[]),F=Object(a.m)(()=>{A(),function(){const e=window.getSelection();e&&(e.removeAllRanges?e.removeAllRanges():e.empty&&e.empty())}()},[A]);function U(){if(d.d)return;const e=window.getSelection();if(!e||!e.rangeCount||S.current)return void A();const t=e.getRangeAt(0),n=t.toString().trim();if(!Object(p.a)(t)||!n||Object(f.a)(n)||!t.START_TO_END)return void A();const a=t.getBoundingClientRect(),r=w.current.getBoundingClientRect();let c=a.left+a.width/2-r.left;c<90?c=90:c>r.width-90&&(c=r.width-90),D({x:c,y:a.top-r.top}),R(t),k()}Object(a.n)(()=>{d.k||P()},[y,P,N,s]),Object(a.n)(()=>{if(T)return;const e=Object(i.a)(e=>{"Tab"===e.key&&(e.preventDefault(),requestAnimationFrame(P))},2e3,!0,!1);return Object(m.a)({onTab:e})},[P,T]),Object(a.n)(()=>{const e=w.current;function t(){e.blur()}return u&&e.addEventListener("focus",t),()=>{e.removeEventListener("focus",t)}},[u]);const B=Object(l.a)("form-control custom-scroll",n.length>0&&"touched",u&&"focus-disabled");return a.a.createElement("div",{id:e,onClick:u?j:void 0},a.a.createElement("div",{ref:w,id:t||c.u,className:B,contentEditable:!0,onClick:P,onChange:function(e){const{innerHTML:t,textContent:n}=e.currentTarget;if(v("
"===t?"":t),!(d.k||n&&n.length)){const e=window.getSelection();e&&(w.current.blur(),e.removeAllRanges(),Object(o.a)(w.current,!0))}},onKeyDown:function(e){"Enter"!==e.key||e.shiftKey?"ArrowUp"!==e.key||n.length?e.target.addEventListener("keyup",(function t(){U(),e.target.removeEventListener("keyup",t)})):(e.preventDefault(),M()):d.d||d.b||!("enter"===C&&!e.shiftKey||"ctrl-enter"===C&&(e.ctrlKey||e.metaKey))||(e.preventDefault(),A(),E())},onMouseDown:function(e){2===e.button?!0!==S.current&&(S.current=!0,document.addEventListener("mousedown",(function e(){setTimeout(()=>{S.current=!1},100),window.removeEventListener("mouseup",e)})),document.addEventListener("keydown",(function e(t){"Esc"!==t.key&&"Escape"!==t.key||(setTimeout(()=>{S.current=!1},100),window.removeEventListener("keydown",e))}))):e.target.addEventListener("mouseup",(function t(){U(),e.target.removeEventListener("mouseup",t)}))},onContextMenu:function(e){d.b&&(e.preventDefault(),e.stopPropagation())},onTouchCancel:function(){d.b&&U()}}),a.a.createElement("div",{ref:I,className:Object(l.a)(B,"clone")}),a.a.createElement("span",{className:"placeholder-text"},r),a.a.createElement(g.a,{isOpen:L,anchorPosition:x,selectedRange:_,onClose:F}))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var a=n(0),r=n(169),c=n(103),s=n(136),i=n(14);function o(e){const t=Object(a.q)();let n=!1;Object(c.a)(()=>{if(n=!0,t.current=void 0,!e)return;const a=new Image;if(a.src=e,!a.width)return;const c=Object(i.f)(a);Object(r.a)(c.getContext("2d"),0,0,c.width,c.height,2,2),t.current=c.toDataURL()},[e]);const o=Object(s.a)(e||void 0,Boolean(t.current));return t.current||!n&&o||e||void 0}},function(e,t,n){"use strict";var a=n(0),r=n(5),c=n(8),s=n(147),i=n(37),o=n(30),l=n(155),u=n(110),d=n(51);n(237);t.a=Object(a.h)(({message:e,senderTitle:t,onMessageClick:n})=>{let m=Object(r.P)(e);if(!m){const t=Object(r.n)(e);if(t){const{url:n,domain:a}=t,c=Object(r.M)(e);m={siteName:a.replace(/^www./,""),url:n.includes("://")?n:n.includes("@")?"mailto:"+n:"http://"+n,description:c!==n?c:void 0}}}const h=Object(a.m)(()=>{n(e.id,e.chatId)},[n,e.id,e.chatId]);if(!m)return;const{siteName:b,url:f,displayUrl:p,title:g,description:O,photo:v}=m,j=!t&&Object(s.a)(O,170),E=Object(c.a)("WebLink scroll-item",!v&&"without-photo");return a.a.createElement("div",{className:E,"data-initial":(b||p)[0]},v&&a.a.createElement(l.a,{message:e}),a.a.createElement("div",{className:"content"},a.a.createElement(u.a,{className:"site-title",onClick:h},Object(i.a)(g||b||p)),j&&a.a.createElement(u.a,{className:"site-description",onClick:h},Object(i.a)(j)),a.a.createElement(d.a,{url:f,className:"site-name",text:""},f.replace("mailto:","")||p),t&&a.a.createElement("div",{className:"sender-name"},Object(i.a)(t))),t&&a.a.createElement("div",{className:"message-date"},a.a.createElement(u.a,{className:"date",onClick:h},Object(o.g)(1e3*e.date))))})},,,,function(e,t,n){"use strict";var a=n(0),r=n(2),c=n(4),s=n(1),i=n(7),o=n(38),l=n(3),u=n(5),d=n(6),m=n(118);let h;!function(e){e[e.Move=0]="Move",e[e.Opacity=1]="Opacity",e[e.None=2]="None"}(h||(h={}));var b=n(102),f=n(16),p=n(94),g=n(179),O=n(37),v=n(9),j=n(8),E=n(132),y=n(160),N=n(28),T=n(97),C=n(101),M=n(123),w=n(148),I=n(161),S=n(149),L=n(95),k=n(44),A=n(164);n(198);var x=({chat:e,isPinned:t})=>{const n=Boolean(e.unreadCount||e.hasUnreadMark||t),r=Object(j.a)("Badge",e.isMuted&&"muted",t&&"pinned",Boolean(e.unreadCount||e.hasUnreadMark)&&"unread");function c(){return e.unreadCount?e.unreadMentionsCount?a.a.createElement("div",{className:"Badge-wrapper"},a.a.createElement("div",{className:"Badge mention"},a.a.createElement("i",{className:"icon-mention"})),a.a.createElement("div",{className:r},Object(k.b)(e.unreadCount))):a.a.createElement("div",{className:r},Object(k.b)(e.unreadCount)):e.hasUnreadMark?a.a.createElement("div",{className:r}):t?a.a.createElement("div",{className:r},a.a.createElement("i",{className:"icon-pinned-chat"})):void 0}return a.a.createElement(A.a,{isCustom:!0,className:"Badge-transition",isOpen:n},c)};n(199);var D,_=Object(a.h)(Object(r.h)((e,{chatId:t})=>{const n=Object(d.f)(e,t);if(!n||!n.lastMessage)return{};const{senderId:a,replyToMessageId:r,isOutgoing:s}=n.lastMessage,i=a?Object(d.Db)(e,a):void 0,o=Object(u.t)(n.lastMessage),l=o&&r?Object(d.k)(e,n.id,r):void 0,{targetUserId:m,targetChatId:h}=o||{},b=Object(u.T)(n),{type:f}=Object(d.y)(e)||{};return{chat:n,lastMessageSender:i,...s&&{lastMessageOutgoingStatus:Object(d.cb)(e,n.lastMessage)},...b&&{privateChatUser:Object(d.Db)(e,b)},...m&&{actionTargetUser:Object(d.Db)(e,m)},actionTargetChatId:h,actionTargetMessage:l,draft:Object(d.B)(e,t,c.MAIN_THREAD_ID),messageListType:f,animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(l.l)(t,["openChat","focusLastMessage"]))(({style:e,chatId:t,folderId:n,orderDiff:r,animationType:c,isSelected:o,isPinned:l,chat:d,privateChatUser:m,actionTargetUser:b,lastMessageSender:f,lastMessageOutgoingStatus:k,actionTargetMessage:A,actionTargetChatId:D,draft:_,messageListType:R,animationLevel:P,lastSyncTime:F,openChat:U,focusLastMessage:B})=>{const q=Object(a.q)(null),[H,$,Y]=Object(N.a)(),{lastMessage:V,typingStatus:K}=d||{},z=V&&Object(u.cb)(V);Object(E.a)(t,z?V.replyToMessageId:void 0,A);const W=V&&!Object(u.L)(V)?Object(u.E)(V):void 0,X=Object(T.a)(V?Object(u.D)(V,"micro"):void 0);Object(a.o)(()=>{if(0===P)return;const e=q.current;if(c===h.Opacity)e.style.opacity="0",Object(v.b)(()=>{e.classList.add("animate-opacity"),e.style.opacity="1"});else{if(c!==h.Move)return;e.style.transform=`translate3d(0, ${100*-r}%, 0)`,Object(v.b)(()=>{e.classList.add("animate-transform"),e.style.transform=""})}setTimeout(()=>{Object(v.b)(()=>{e.classList.remove("animate-opacity","animate-transform"),e.style.opacity="",e.style.transform=""})},200+s.c)},[P,r,c]);const G=Object(a.m)(()=>{U({id:t}),o&&"thread"===R&&B()},[o,R,U,t,B]),Q=Object(y.a)({chat:d,privateChatUser:m,handleDelete:$,folderId:n,isPinned:l}),J=Object(p.a)();if(!d)return;const Z=Object(j.a)("Chat chat-item-clickable",Object(u.kb)(t)?"private":"group",o&&!i.f&&"selected");return a.a.createElement(L.a,{ref:q,className:Z,style:e,ripple:!i.f,contextActions:Q,onClick:G},a.a.createElement(C.a,{chat:d,user:m,withOnlineStatus:!0,isSavedMessages:m&&m.isSelf,lastSyncTime:F}),a.a.createElement("div",{className:"info"},a.a.createElement("div",{className:"title"},a.a.createElement("h3",null,Object(O.a)(Object(u.l)(d,m))),d.isVerified&&a.a.createElement(M.a,null),d.isMuted&&a.a.createElement("i",{className:"icon-muted-chat"}),d.lastMessage&&a.a.createElement(I.a,{message:d.lastMessage,outgoingStatus:k})),a.a.createElement("div",{className:"subtitle"},function(){if(K&&V&&K.timestamp>1e3*V.date)return a.a.createElement(w.a,{typingStatus:K});if(_&&_.text.length)return a.a.createElement("p",{className:"last-message"},a.a.createElement("span",{className:"draft"},J("Draft")),Object(O.a)(_.text));if(!V)return;if(z){const e=d&&(Object(u.ib)(d)||V.senderId===V.chatId)?d:f;return a.a.createElement("p",{className:"last-message"},Object(O.a)(Object(g.a)(V,e,b,A,D,{asPlain:!0})))}const e=Object(u.I)(t,f);return a.a.createElement("p",{className:"last-message"},e&&a.a.createElement("span",{className:"sender-name"},Object(O.a)(e)),function(e,t){if(!t)return Object(O.a)(Object(u.M)(e));return a.a.createElement("span",{className:"media-preview"},a.a.createElement("img",{src:t,alt:""}),Object(u.O)(e)&&a.a.createElement("i",{className:"icon-play"}),Object(O.a)(Object(u.M)(e,!0)))}(V,X||W))}(),a.a.createElement(x,{chat:d,isPinned:l}))),a.a.createElement(S.a,{isOpen:H,onClose:Y,chat:d}))}));!function(e){e.all="active",e.archived="archived"}(D||(D={}));t.a=Object(a.h)(Object(r.h)((e,{folderType:t,folderId:n})=>{const{chats:{listIds:a,byId:r,orderedPinnedIds:s},users:{byId:i},lastSyncTime:o}=e,{chatId:l,threadId:u}=Object(d.y)(e)||{},m="folder"!==t?D[t]:void 0,h=n?Object(d.i)(e,n):void 0;return{chatsById:r,usersById:i,currentChatId:l,lastSyncTime:o,...m?{listIds:a[m],orderedPinnedIds:s[m]}:{chatFolder:h},isInDiscussionThread:u!==c.MAIN_THREAD_ID}},(e,t)=>Object(l.l)(t,["loadMoreChats","preloadTopChatMessages"]))(({folderType:e,folderId:t,noChatsText:n="Chat list is empty.",chatFolder:r,chatsById:c,usersById:d,listIds:p,currentChatId:g,orderedPinnedIds:O,lastSyncTime:v,isInDiscussionThread:j,loadMoreChats:E,preloadTopChatMessages:y})=>{const[N,T]=Object(a.p)(()=>"folder"===e&&r?Object(u.Ab)(c,d,r):[p,O],[e,c,d,r,p,O]),[C,M]=Object(a.p)(()=>{if(!N||"folder"===e&&!r)return[];const t=Object(u.zb)(c,N,T,e),n=[...t.pinnedChats,...t.otherChats],a=n.map(({id:e})=>e);return[n.reduce((e,t,n)=>(e[t.id]=n,e),{}),a]},[N,T,e,r,c]),w=Object(o.a)(C),I=C&&w?Object(l.i)(C,(e,t)=>e-(void 0!==w[t]?w[t]:1/0)):{},S=Object(a.m)(()=>{E({listType:"archived"===e?"archived":"active"})},[E,e]),[L,k]=Object(m.a)(v?S:void 0,M,void 0,s.j,"all"===e&&!s.a),A=L&&Object(u.zb)(c,L,T,e);Object(a.n)(()=>{v&&"all"===e&&y()},[v,e,y]);const x=function(e){const t=Object(a.m)(t=>e[t]<0,[e]),n=Object(a.m)(t=>e[t]>0,[e]),r=Object.keys(e).map(Number),c=r.filter(t).length,s=r.filter(n).length;return Object(a.m)(a=>{const r=e[a];return 0===r?h.None:r===1/0||r===-1/0||t(a)&&c<=s||n(a)&&sa.a.createElement(_,{key:n,teactOrderKey:r,chatId:n,isPinned:!0,folderId:t,isSelected:n===g&&!j,animationType:x(n),orderDiff:I[n],style:`top: ${(e+r)*s.h}px;`})),A.otherChats.map((e,r)=>a.a.createElement(_,{key:e.id,teactOrderKey:Object(u.j)(e),chatId:e.id,folderId:t,isSelected:e.id===g&&!j,animationType:x(e.id),orderDiff:I[e.id],style:`top: ${(n+r)*s.h}px;`})))}():L&&!L.length?a.a.createElement("div",{className:"no-results"},n):a.a.createElement(f.a,{key:"loading"}))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var a=n(0),r=n(5),c=n(147),s=n(37),i=n(2),o=n(3),l=n(8),u=n(110);var d=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:r})=>{const c=Object(a.m)(()=>{t&&n({id:t.id})},[t,n]);return t?a.a.createElement(u.a,{className:Object(l.a)("UserLink",e),onClick:c},r):r});var m=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:r})=>{const c=Object(a.m)(()=>{t&&r({chatId:t.chatId,messageId:t.id})},[r,t]);return t?a.a.createElement(u.a,{className:Object(l.a)("MessageLink",e),onClick:c},n):n});var h=Object(i.h)(void 0,(e,t)=>Object(o.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:r})=>{const c=Object(a.m)(()=>{t&&n({id:t})},[t,n]);return t?a.a.createElement(u.a,{className:Object(l.a)("ChatLink",e),onClick:c},r):r});function b(e,t,n,i,o,l={}){if(!e.content.action)return[];const{text:u}=e.content.action,d=[],b={...l,maxTextLength:16};let g,O=p(u,"%action_origin%",t?!l.isEmbedded&&(v=t,j=l.asPlain,Object(r.eb)(v)?function(e,t){const n=Object(c.a)(Object(r.l)(e));return t?n:a.a.createElement(h,{className:"action-link",chatId:e.id},e&&Object(s.a)(n))}(v,j):f(v,j))||" ":"User");var v,j;return g=O.pop(),d.push(...O),O=p(g,"%target_user%",n?f(n,l.asPlain):"User"),g=O.pop(),d.push(...O),O=p(g,"%message%",i?function(e,t={}){const n=Object(r.M)(e),{photo:i,video:o,document:l,sticker:u}=Object(r.v)(e),d=n&&!i&&!o&&!l&&!u;let h=Object(c.a)(n,t.maxTextLength);i?h="a photo":o?h=o.isGif?"a GIF":"a video":l?h="a document":u&&(h=`«${n}»`);if(t.asPlain)return d?`«${h}»`:h;if(d)return a.a.createElement("span",null,"«",a.a.createElement(m,{className:"action-link",message:e},Object(s.a)(h)),"»");return a.a.createElement(m,{className:"action-link",message:e},Object(s.a)(h))}(i,b):"a message"),g=O.pop(),d.push(...O),O=p(g,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),g=O.pop(),d.push(...O),O=p(g,"%target_chat%",o?function(e,t){if(t)return"another chat";return a.a.createElement(h,{className:"action-link",chatId:e},"another chat")}(o,l.asPlain):"another chat"),d.push(...O),l.asPlain?d.join("").trim():d}function f(e,t){const n=Object(c.a)(Object(r.Y)(e));return t?n:a.a.createElement(d,{className:"action-link",sender:e},e&&Object(s.a)(n))}function p(e,t,n){const a=e.indexOf(t);if(a<0||!n)return[e];const r=[];return r.push(e.substring(0,a)),r.push(n),r.push(e.substring(a+t.length)),r}},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var a=n(0),r=n(4),c=n(1),s=n(5),i=n(46);var o=n(7),l=n(126),u=n(28);const d=/[^@_\d\wа-яё]+/i;function m(e,t,n,m=c.u,h,b,f){const[p,g,O]=Object(u.a)(),[v,j]=Object(a.r)(""),[E,y]=Object(a.r)([]),N=Object(a.m)(e=>{if(h&&f)return h.filter(({userId:t})=>{const n=f[t];return!(t===b||!n)&&(!e||function(e,t){const n=t.username.toLowerCase(),a=Object(s.Y)(t),r=a&&a.toLowerCase(),c=e.toLowerCase();return n.startsWith(c)||r&&Object(i.a)(r,c)}(e,n))})},[h,b,f]);Object(a.n)(()=>{if(!e||!t.length)return void O();const n=function(e){const t=document.createElement("div");t.innerHTML=e;const n=t.innerText,a=n[n.length-1],r=n.split(d).pop();if(!n.length||d.test(a)||!r||!r.startsWith("@"))return;return r}(t);if(n){const e=n?n.substr(1):"",t=N(e);t&&t.length?(g(),j(e),y(t)):O()}else O()},[e,t,N,g,O]);const T=Object(a.m)((e,a=!1)=>{if(!e.username&&!Object(s.X)(e))return;const c=e.username?"@"+e.username:`${Object(s.X)(e)}`,i=t.lastIndexOf("@");if(-1!==i){n(`${t.substr(0,i)}${c} `);const e=document.getElementById(m);o.f||requestAnimationFrame(()=>{Object(l.a)(e,a)})}O()},[t,m,n,O]);return{isMentionMenuOpen:p,mentionFilter:v,closeMentionMenu:O,insertMention:T,mentionFilteredMembers:E}}},,function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},,,,function(e,t,n){},function(e,t,n){},function(e,t,n){},,,function(e,t,n){},,function(e,t,n){},function(e,t,n){},,,,,,,,,,,,function(e,t,n){},,,,,,,,function(e,t,n){},function(e,t,n){},function(e,t,n){}])]); +//# sourceMappingURL=0.9a2173a5ef629d3739fc.js.map \ No newline at end of file diff --git a/dist/0.9a2173a5ef629d3739fc.js.map b/dist/0.9a2173a5ef629d3739fc.js.map new file mode 100644 index 00000000..fd1c29d6 --- /dev/null +++ b/dist/0.9a2173a5ef629d3739fc.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///./src/hooks/useLang.ts","webpack:///./src/components/ui/ListItem.tsx","webpack:///./src/hooks/useIntersectionObserver.ts","webpack:///./src/hooks/useMedia.ts","webpack:///./src/components/common/PrivateChatInfo.tsx","webpack:///./src/components/ui/Modal.tsx","webpack:///./src/util/trapFocus.ts","webpack:///./src/components/ui/Transition.tsx","webpack:///./src/components/common/Avatar.tsx","webpack:///./src/components/ui/InfiniteScroll.tsx","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/hooks/useTransitionForMedia.ts","webpack:///./src/components/common/helpers/mediaDimensions.ts","webpack:///./src/components/common/AnimatedSticker.tsx","webpack:///./src/components/ui/ConfirmDialog.tsx","webpack:///./src/components/common/NothingFound.tsx","webpack:///./src/components/right/hooks/useAsyncRendering.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/hooks/useMediaWithDownloadProgress.ts","webpack:///./src/components/ui/ProgressSpinner.tsx","webpack:///./src/components/ui/Portal.ts","webpack:///./src/components/common/GroupChatInfo.tsx","webpack:///./src/util/fastSmoothScroll.ts","webpack:///./src/components/ui/Radio.tsx","webpack:///./src/components/ui/RadioGroup.tsx","webpack:///./src/hooks/useInfiniteScroll.ts","webpack:///./src/components/common/AnimatedEmoji.tsx","webpack:///./src/hooks/useBackgroundMode.ts","webpack:///./src/util/captureEvents.ts","webpack:///./src/components/common/VerifiedIcon.tsx","webpack:///./src/util/safePlay.ts","webpack:///./src/hooks/useBuffering.ts","webpack:///./src/util/focusEditableElement.ts","webpack:///./src/components/middle/composer/helpers/parseMessageInput.ts","webpack:///./src/components/middle/composer/DropTarget.tsx","webpack:///./src/components/middle/composer/DropArea.tsx","webpack:///./src/components/common/PickerSelectedItem.tsx","webpack:///./src/hooks/useHorizontalScroll.ts","webpack:///./src/hooks/useEnsureMessage.ts","webpack:///./src/hooks/useContextMenuHandlers.ts","webpack:///./src/util/cycleRestrict.ts","webpack:///./src/components/common/helpers/renderMessageText.tsx","webpack:///./src/hooks/useBlur.ts","webpack:///./src/hooks/useVideoCleanup.ts","webpack:///./src/util/clipboard.ts","webpack:///./src/components/ui/SearchInput.tsx","webpack:///./src/util/fastSmoothScrollHorizontal.ts","webpack:///./src/util/resetScroll.ts","webpack:///./src/util/trimText.ts","webpack:///./src/components/common/TypingStatus.tsx","webpack:///./src/components/common/DeleteChatModal.tsx","webpack:///./src/util/patchSafariProgressiveAudio.ts","webpack:///./src/hooks/useLayoutEffectWithPrevDeps.ts","webpack:///./src/components/common/Document.tsx","webpack:///./src/components/common/StickerSetModal.async.tsx","webpack:///./src/components/middle/composer/TextFormatter.tsx","webpack:///./src/components/common/Media.tsx","webpack:///./src/components/common/Audio.tsx","webpack:///./src/util/waveform.ts","webpack:///./src/components/common/helpers/waveform.ts","webpack:///./src/components/ui/Tab.tsx","webpack:///./src/components/ui/TabList.tsx","webpack:///./src/util/getReadableErrorText.ts","webpack:///./src/hooks/useChatContextActions.ts","webpack:///./src/components/common/LastMessageMeta.tsx","webpack:///./src/components/common/MessageOutgoingStatus.tsx","webpack:///./src/hooks/useContextMenuPosition.ts","webpack:///./src/components/ui/ShowTransition.tsx","webpack:///./src/hooks/useAudioPlayer.ts","webpack:///./src/util/audioPlayer.ts","webpack:///./src/util/download.ts","webpack:///./src/components/common/File.tsx","webpack:///./src/lib/fastBlur.js","webpack:///./src/components/ui/Notification.tsx","webpack:///./src/components/middle/composer/helpers/selection.ts","webpack:///./src/components/middle/composer/MessageInput.tsx","webpack:///./src/hooks/useBlurSync.ts","webpack:///./src/components/common/WebLink.tsx","webpack:///./src/components/left/main/hooks/useChatAnimationType.ts","webpack:///./src/components/left/main/Badge.tsx","webpack:///./src/components/left/main/Chat.tsx","webpack:///./src/components/left/main/ChatList.tsx","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/components/middle/composer/hooks/useMentionMenu.ts","webpack:///./src/components/middle/composer/helpers/searchUserName.ts"],"names":["forceUpdate","useForceUpdate","useOnChange","langProvider","ListItem","props","ref","icon","className","style","children","disabled","ripple","narrow","inactive","focus","destructive","multiline","contextActions","onClick","containerRef","useRef","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","getTriggerElement","useCallback","current","getRootElement","closest","getMenuElement","querySelector","positionX","positionY","menuStyle","useContextMenuPosition","handleClick","e","handleMouseDown","IS_TOUCH_ENV","button","fullClassName","buildClassName","role","tabIndex","undefined","onMouseDown","onContextMenu","isOpen","autoClose","onClose","onCloseAnimationEnd","map","action","key","title","handler","useIntersectionObserver","rootRef","throttleMs","debounceMs","shouldSkipFirst","margin","threshold","isDisabled","rootCallback","controllerRef","rootCallbackRef","isFrozenRef","onUnfreezeRef","freeze","unfreeze","useHeavyAnimationCheck","useEffect","observer","disconnect","callbacks","clear","observe","target","targetCallback","Map","entriesAccumulator","observerCallbackSync","entries","Array","from","values","forEach","entry","callback","get","scheduler","throttle","debounce","observerCallback","IntersectionObserver","set","root","rootMargin","initController","controller","delete","unobserve","useOnIntersect","targetRef","useIsIntersecting","isIntersecting","setIsIntersecting","useState","mediaHash","noLoad","mediaFormat","ApiMediaFormat","BlobUrl","cacheBuster","delay","mediaData","mediaLoader","startedAt","Date","now","then","spentTime","setTimeout","memo","withGlobal","global","userId","forceShowSelf","lastSyncTime","user","selectUser","isSavedMessages","isSelf","areMessagesLoaded","Boolean","selectChatMessages","setGlobal","actions","pick","typingStatus","avatarSize","status","withMediaViewer","withUsername","withFullInfo","withUpdatingStatus","noStatusOrTyping","loadFullUser","openMediaViewer","id","fullName","getUserFullName","handleAvatarViewerOpen","hasPhoto","stopPropagation","avatarOwnerId","origin","MediaViewerOrigin","ProfileAvatar","MiddleHeaderAvatar","lang","useLang","size","renderText","isVerified","isUserOnline","username","getUserStatus","Modal","header","hasCloseButton","noBackdrop","onEnter","shouldRender","transitionClassNames","useShowTransition","modalRef","captureKeyboardListeners","onEsc","element","handleKeyDown","preventDefault","focusableElements","querySelectorAll","length","currentFocusedIndex","findIndex","em","isSameNode","document","activeElement","newFocusedIndex","shiftKey","addEventListener","removeEventListener","trapFocus","useEffectWithPrevDeps","prevIsOpen","body","classList","toggle","dispatchHeavyAnimationEvent","remove","Portal","Button","round","color","ariaLabel","ANIMATION_DURATION","slide","fade","IS_MOBILE_SCREEN","reveal","CLEANED_UP","Symbol","animationLevel","settings","byKey","activeKey","name","direction","renderCount","shouldRestoreHeight","shouldCleanup","onStart","onStop","rendersRef","prevActiveKey","usePrevious","activateTimeoutRef","activeKeyChanged","useLayoutEffect","cleanup","container","childElements","add","childNodes","clearTimeout","isBackwards","keys","Object","Number","prevActiveIndex","indexOf","activeIndex","node","i","HTMLElement","width","offsetWidth","scrollBy","left","behavior","ANIMATION_END_DELAY","requestAnimationFrame","window","scrollLeft","height","clientHeight","renders","contents","fill","render","chat","text","withOnlineStatus","isDeleted","isDeletedUser","imageHash","getChatAvatarHash","dataUri","useMedia","DataUri","shouldRenderFullMedia","useTransitionForMedia","content","src","alt","decoding","userFullName","getFirstLetters","getChatTitle","isChatPrivate","isOnline","getUserColorKey","senderId","data-test-sender-id","IS_TEST","InfiniteScroll","onLoadMore","onScroll","items","itemSelector","preloadBackwards","sensitiveArea","noScrollRestore","noFastList","stateRef","loadMoreBackwards","loadMoreForwards","useMemo","LoadMoreDirection","Backwards","Forwards","scrollHeight","state","listItemElements","newScrollTop","currentAnchor","includes","scrollTop","getBoundingClientRect","top","currentAnchorTop","nextAnchor","offsetParent","resetScroll","isScrollTopJustUpdated","handleScroll","listLength","offsetHeight","isNearTop","offsetTop","isNearBottom","isUpdated","nextAnchorTop","newAnchorTop","teactFastList","cb","dependencies","prevDeps","some","d","SPEED","fast","slow","speed","noAnimate","isMediaLoaded","willAnimate","shouldRenderThumb","setShouldRenderThumb","MEDIA_VIEWER_MEDIA_QUERY","REM","parseInt","getComputedStyle","documentElement","fontSize","ROUND_VIDEO_DIMENSIONS","AVATAR_FULL_DIMENSIONS","DEFAULT_MEDIA_DIMENSIONS","cachedMaxWidth","getAvailableWidth","fromOwnMessage","isForwarded","isWebPagePhoto","extraPaddingRem","regularMaxWidth","Math","min","floor","innerWidth","getMaxMessageWidthRem","calculateDimensionsForMessageMedia","isGif","aspectRatio","calculateDimensions","getAvailableHeight","getMediaViewerAvailableDimensions","withFooter","isVideo","mql","matchMedia","windowWidth","windowHeight","windowSize","occupiedHeightRem","matches","calculateInlineImageDimensions","photo","getPhotoInlineDimensions","calculateVideoDimensions","video","getVideoDimensions","getPictogramDimensions","getDocumentThumbnailDimensions","smaller","getStickerDimensions","sticker","baseWidth","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_INLINE_DESKTOP_FACTOR","calculatedHeight","calculateMediaViewerDimensions","availableWidth","availableHeight","mediaWidth","mediaHeight","calculatedWidth","lottiePromise","RLottie","async","ensureLottie","default","animationData","play","playSegment","noLoop","quality","isLowPriority","onLoad","animation","setAnimation","wasPlaying","isFrozen","playRef","playSegmentRef","exec","newAnimation","setSpeed","fastRaf","destroy","playAnimation","shouldRestart","goToAndPlay","pauseAnimation","pause","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","useBackgroundMode","IS_IOS","textParts","confirmLabel","confirmHandler","confirmIsDestructive","isButtonsInOneRow","split","textPart","isText","useAsyncRendering","shouldRenderRef","timeoutRef","Link","href","isStreaming","Stream","IS_PROGRESSIVE_SUPPORTED","Progressive","downloadProgress","setDownloadProgress","startedAtRef","handleProgress","progress","RADIUSES","s","m","l","xl","square","transparent","noCross","radius","circleRadius","STROKE_WIDTH","borderRadius","circumference","PI","svg","firstElementChild","strokeDashOffset","max","setAttribute","toString","innerHTML","containerId","elementRef","createElement","appendChild","TeactDOM","removeChild","chatId","selectChat","onlineCount","selectChatOnlineCount","withChatType","loadFullChat","isSuperGroup","isChatSuperGroup","isMin","isRestricted","getChatTypeString","handle","groupStatus","chatTypeString","membersCount","getGroupStatus","onlineStatus","renderStatusOrTyping","isAnimating","fastSmoothScroll","position","maxDistance","forceDirection","forceDuration","forceCurrentContainerHeight","FocusDirection","Static","scrollIntoView","block","offset","Up","Down","elementTop","elementHeight","containerHeight","targetContainerHeight","dataset","normalHeight","path","remainingPath","duration","abs","startAt","animateSingle","t","currentPath","transition","scrollWithJs","isAnimatingScroll","label","subLabel","value","checked","hidden","isLoading","onChange","type","Spinner","options","selected","loadingOption","handleChange","event","currentTarget","option","getViewportSlice","sourceIds","offsetId","listSlice","index","indexForDirection","to","newViewportIds","slice","areSomeLocal","areAllLocal","listIds","forceFullPreload","lastParamsRef","viewportIdsRef","prevListIds","prevIsDisabled","areSortedArraysEqual","viewportIds","getMore","AnimatedEmoji","isInline","observeIntersection","isAnimationLoaded","markAnimationLoaded","useFlag","localMediaHash","previewBlobUrl","Lottie","playKey","setPlayKey","String","random","STICKER_SIZE_TWO_FA","onBlur","onFocus","hasFocus","SwipeDirection","captureEvents","captureEvent","hasMoved","onCapture","excludedClosestSelector","onMove","onRelease","pageX","touches","pageY","withCursor","dragOffsetX","dragOffsetY","onDrag","onSwipe","xAbs","yAbs","Left","Right","processSwipe","passive","VerifiedIcon","mediaEl","catch","err","DEBUG","console","warn","noInitiallyBuffered","isBuffered","setIsBuffered","bufferedProgress","setBufferedProgress","setIsBufferedDebounced","handleBuffering","media","isSafariPatchInProgress","buffered","end","readyState","currentTime","bufferingHandlers","onLoadedData","onPlaying","onLoadStart","onPause","onTimeUpdate","onProgress","checkBuffering","focusEditableElement","force","selection","getSelection","range","createRange","lastChild","nodeValue","setStart","removeAllRanges","addRange","ENTITY_CLASS_BY_NODE_NAME","B","ApiMessageEntityTypes","Bold","STRONG","I","Italic","EM","U","Underline","S","Strike","STRIKE","DEL","CODE","Code","PRE","Pre","BLOCKQUOTE","Blockquote","parseMessageInput","html","fragment","parsedHtml","IS_EMOJI_SUPPORTED","replace","parseMarkdown","innerText","trim","textIndex","recursionDeepness","entities","addEntity","entity","rawText","nodeName","anchor","entityType","MentionName","startsWith","Email","Phone","textContent","TextUrl","Url","getEntityTypeFromNode","rawIndex","substring","url","getEntityDataFromNode","push","hasChildNodes","isQuick","onFileSelect","isHovered","markHovered","unmarkHovered","onDrop","onDragEnter","onDragLeave","relatedTarget","toTarget","DropAreaState","withQuick","onHide","hideTimeoutRef","prevWithQuick","captureEscKeyListener","handleFilesDrop","dataTransfer","dt","files","handleQuickFilesDrop","handleDragLeave","fromTarget","onDragOver","chatOrUserId","isMinimized","canClose","clickArg","iconElement","titleText","getUserFirstOrLastName","deltaX","deltaY","messageId","message","replyOriginForId","loadMessage","getDispatch","loadMessageThrottled","throttled","contextMenuCounter","isMenuDisabled","setIsContextMenuOpen","setContextMenuPosition","x","clientX","y","clientY","timer","clearLongPressTimer","startLongPressTimer","contains","originalEvent","cancelClickOnce","stopImmediatePropagation","emulateContextMenuEvent","cycleRestrict","renderMessageText","highlight","shouldRenderHqEmoji","formattedText","getMessageText","renderTextWithEntities","organizeEntities","organizedEntityIndexes","Set","organizedEntities","has","organizedEntity","organizeEntity","organizedIndexes","nestedEntities","filter","organizedIndex","shouldRenderAsHtml","renderMessagePart","result","deleteLineBreakAfterPre","organizedEntites","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","join","getLinkUrl","processEntityAsHtml","entityText","BotCommand","handleBotCommandClick","Hashtag","Cashtag","handleHashtagClick","rel","Mention","processEntity","isArray","textAfter","arrayIndex","c","emojiFilter","sendBotCommand","command","setLocalTextSearchQuery","query","searchTextMessagesLocal","cache","useBlur","blurredRef","img","Image","onload","canvas","imgToCanvas","fastBlur","getContext","blurredDataUri","toDataURL","useVideoCleanup","videoRef","videoEl","load","CLIPBOARD_ITEM_SUPPORTED","navigator","clipboard","ClipboardItem","textCopyEl","copyTextToClipboard","str","rangeToRestore","rangeCount","getRangeAt","select","execCommand","copyImageToClipboard","imageUrl","ctx","imageEl","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","error","inputId","focused","placeholder","onReset","inputRef","isInputFocused","markInputFocused","unmarkInputFocused","blur","containerWidth","scrollWidth","animate","scrollTo","overflow","trimText","typingUser","typingUserName","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","canDeleteForAll","contactName","getPrivateChatUserId","isChannel","isChatChannel","isBasicGroup","isChatBasicGroup","chatTitle","leaveChannel","deleteHistory","deleteChannel","handleDeleteMessageForAll","maxId","lastMessage","shouldDeleteForAll","handleDeleteChat","isCreator","patchSafariProgressiveAudio","audioEl","patchedForSafari","patchForSafariInProgress","paused","once","uploadProgress","withDate","datetime","sender","isSelected","isSelectable","onCancelUpload","onDateClick","extension","getDocumentExtension","fileName","timestamp","isDownloadAllowed","setIsDownloadAllowed","useMediaWithDownloadProgress","getMessageMediaHash","isUploading","isTransferring","transferProgress","getMediaTransferState","hasPreview","getDocumentHasPreview","thumbDataUri","getMessageMediaThumbDataUri","localBlobUrl","previewData","isAllowed","handleDateClick","download","thumbnailDataUri","StickerSetModalAsync","StickerSetModal","useModuleLoader","Bundles","Extra","TEXT_FORMAT_BY_TAG_NAME","anchorPosition","selectedRange","linkUrlInputRef","isLinkControlOpen","openLinkControl","closeLinkControl","linkUrl","setLinkUrl","isEditingLink","setIsEditingLink","inputClassName","setInputClassName","selectedTextFormats","setSelectedTextFormats","useVirtualBackdrop","selectedFormats","parentElement","commonAncestorContainer","EDITABLE_INPUT_ID","textFormat","tagName","getSelectedText","getSelectedElement","updateInputStyles","input","getFormatButtonClassName","fKey","monospace","strikethrough","handleBoldText","bold","handleItalicText","italic","handleUnderlineText","underline","handleStrikethroughText","replaceWith","handleMonospaceText","handleLinkUrlConfirm","formattedLinkUrl","restoreSelection","KeyK","KeyB","KeyU","KeyI","KeyM","KeyS","code","altKey","ctrlKey","metaKey","linkUrlConfirmClassName","onKeyDown","autoComplete","inputMode","idPrefix","mediaBlobUrl","getMessageVideo","formatMediaDuration","MIN_SPIKES","MAX_SPIKES","renderSeekline","playProgress","handleStartSeek","handleSeek","handleStopSeek","onMouseMove","onMouseUp","theme","senderTitle","renderingFor","date","onPlay","onReadMedia","audio","voice","isMediaUnread","isVoice","isSeeking","isActivated","setIsActivated","shouldDownload","getMessageMediaFormat","useBuffering","playPause","setCurrentTime","useAudioPlayer","getMessageKey","getMediaDuration","isMessageLocal","shouldRenderSpinner","spinnerClassNames","handleButtonClick","seekBar","seekHandlers","isOwn","isOwnMessage","renderedWaveform","waveform","fillColor","fillOwnColor","progressFillColor","progressFillOwnColor","durationFactor","spikesCount","decodedWaveform","encoded5bit","bitsCount","valuesCount","bitsData","byteIndex","bitShift","lastByteIndex","lastBitShift","lastValue","decodeWaveform","Uint8Array","data","spikes","peak","fitCount","newData","springFactor","leftFiller","rightFiller","idx","val","interpolateArray","fillStyle","progressFillStyle","scale","item","globalAlpha","spikeHeight","beginPath","moveTo","arcTo","closePath","roundedRectangle","renderWaveformToDataUri","draggable","renderWaveform","buttonClassNames","showSeekline","contentClassName","ProgressSpinner","getFirstLine","formatPastTimeShort","performer","getSecondLine","formatMediaDateTime","renderAudio","renderVoice","active","badgeCount","isBadgeActive","previousActiveTab","tabRef","tab","indicator","currentIndicator","shiftLeft","offsetLeft","scaleFactor","clientWidth","transform","tabs","activeTab","onSwitchTab","useHorizontalScroll","activeTabElement","newLeft","fastSmoothScrollHorizontal","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","LINK_NOT_MODIFIED","SERVICE_WORKER_DISABLED","CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","reduce","acc","privateChatUser","handleDelete","folderId","isPinned","toggleChatPinned","updateChatMutedState","toggleChatArchived","toggleChatUnread","actionUnreadMark","unreadCount","hasUnreadMark","actionPin","actionMute","isMuted","actionArchive","isChatArchived","getCanDeleteChat","LastMessageMeta","outgoingStatus","Keys","MessageOutgoingStatus","extraPaddingX","extraTopPadding","setPositionX","setPositionY","setStyle","triggerEl","emptyRect","menuEl","rootEl","triggerRect","menuRect","rootRect","ShowTransition","isCustom","prevChildren","fromChildrenRef","trackId","originalDuration","handlers","onInit","shouldPlay","onForcePlay","noPlaylist","setIsPlaying","isPlayingSync","setPlayProgress","register","eventName","proxy","isFinite","prevShouldPlay","prevSrc","audioProxy","tracks","currentTrackId","queue","stopCurrentAudio","currentTrack","Audio","handleEvent","nextTrackId","openAudioPlayer","parseMessageKey","nextTrack","safePlay","Proxy","createAudio","preload","IS_SAFARI","time","shouldRemoveFromQueue","track","h","filename","link","click","shouldSpinnerRender","getColorFromExtension","sizeString","getFileSizeString","mul_table","shg_table","boxBlurCanvasRGB","context","top_x","top_y","iterations","isNaN","imageData","getImageData","pixels","rsum","gsum","bsum","p","p1","p2","yp","yi","yw","wm","hm","rad1","r","g","b","mul_sum","shg_sum","vmin","vmax","putImageData","onDismiss","setIsOpen","timerRef","closeAndDismiss","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","isSelectionInsideInput","selectionRange","parentNode","MAX_INPUT_HEIGHT","currentChatId","threadId","selectCurrentMessageList","messageSendKeyCombo","replyingToId","selectReplyingToId","noTabCapture","isPollModalOpen","payment","isPaymentModalOpen","editableInputId","shouldSetFocus","shouldSupressFocus","onUpdate","onSupressedFocus","onSend","editLastMessage","cloneRef","isContextMenuOpenRef","isTextFormatterOpen","openTextFormatter","closeTextFormatter","textFormatterAnchorPosition","setTextFormatterAnchorPosition","setSelectedRange","useLayoutEffectWithPrevDeps","prevHtml","willSend","clone","currentHeight","newHeight","transitionDuration","log","updateInputHeight","focusInput","handleCloseTextFormatter","empty","clearSelection","checkSelection","selectedText","parseEmojiOnlyString","START_TO_END","selectionRect","inputRect","captureFirstTab","onTab","supressFocus","contentEditable","handleKeyUp","IS_ANDROID","closeContextMenuMouseListener","closeContextMenuKeyListener","handleMouseUp","onTouchCancel","useBlurSync","isChanged","blurredAsync","onMessageClick","linkData","getMessageWebPage","getFirstLinkInMessage","domain","messageText","getMessageSummaryText","siteName","description","handleMessageClick","displayUrl","truncatedDescription","data-initial","ChatAnimationTypes","Badge","isShown","renderContent","unreadMentionsCount","formatIntegerCompact","FolderTypeToListType","replyToMessageId","isOutgoing","lastMessageSender","lastMessageAction","getMessageAction","actionTargetMessage","selectChatMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","privateChatUserId","messageListType","lastMessageOutgoingStatus","selectOutgoingStatus","actionTargetUser","draft","selectDraft","MAIN_THREAD_ID","orderDiff","animationType","openChat","focusLastMessage","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isAction","isActionMessage","useEnsureMessage","mediaThumbnail","getMessageSticker","Opacity","opacity","Move","useChatContextActions","Avatar","TypingStatus","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","blobUrl","renderMessageSummary","renderLastMessageOrTyping","DeleteChatModal","folderType","chats","byId","chatsById","orderedPinnedIds","users","usersById","currentThreadId","listType","chatFolder","selectChatFolder","isInDiscussionThread","noChatsText","loadMoreChats","preloadTopChatMessages","currentListIds","currentPinnedIds","prepareFolderListIds","orderById","orderedIds","newChatArrays","prepareChatList","singleList","pinnedChats","otherChats","newOrderedIds","prevOrderById","orderDiffById","mapValues","order","Infinity","loadMoreOfType","useInfiniteScroll","CHAT_LIST_SLICE","ALL_CHATS_PRELOAD_DISABLED","chatArrays","getAnimationType","movesUp","movesDown","orderDiffIds","numberOfUp","numberOfDown","None","useChatAnimationType","viewportOffset","pinnedOffset","CHAT_HEIGHT_PX","teactOrderKey","getChatOrder","renderChats","Loading","openUserInfo","focusMessage","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","isChat","renderChatContent","renderUserContent","pop","getMessageContent","showQuotes","renderMessageContent","invoice","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","RE_NOT_USERNAME_SEARCH","useMentionMenu","canSuggestMembers","onUpdateHtml","groupChatMembers","currentUserId","markIsOpen","unmarkIsOpen","currentFilter","setCurrentFilter","filteredMembers","setFilteredMembers","getFilteredMembers","usernameLowered","toLowerCase","fullNameLowered","filterLowered","searchWords","searchUserName","usernameFilter","tempEl","lastSymbol","lastWord","test","getUsernameFilter","membersToMention","insertMention","forceFocus","insertedHtml","atIndex","lastIndexOf","messageInput","getElementById","isMentionMenuOpen","mention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EAAiBA,EAAeltB,OAAO,GAAK,GACrDwtB,EAAmBb,EAAmBztB,GACxCsuB,GAAoBA,EAAiB/yC,QACvC4xC,IACAG,EAAiBttB,GACjBwtB,EAAmBc,IAEnBlB,SAGFA,KAED,CAACL,EAAmBtzB,EAAMg0B,EAAoBN,EAAYC,IAE7D,MAAMmB,EAAgBh9C,YAAY,CAACyG,EAAew2C,GAAa,KAC7D,IAAKx2C,EAAKqC,WAAaijB,YAAuBtlB,GAC5C,OAGF,MAAMy2C,EAAez2C,EAAKqC,SACrB,IAAGrC,EAAKqC,SACR,uEAEqBie,wBAAsBoC,yCAC1B1iB,EAAKoB,oDAEpBkkB,YAAuBtlB,SAExB02C,EAAUj1B,EAAKk1B,YAAY,KACjC,IAAiB,IAAbD,EAAgB,CAClB1B,EAAc,GAAEvzB,EAAKqH,OAAO,EAAG4tB,KAAWD,WAC1C,MAAMG,EAAehzC,SAASizC,eAAetpB,GACxCroB,KACH2C,sBAAsB,KACpB4X,YAAqBm3B,EAAcJ,KAKzCpB,KACC,CAAC3zB,EAAM8L,EAASynB,EAAcI,IAEjC,MAAO,CACL0B,kBAAmBj8C,EACnBk8C,cAAe1B,EACf2B,iBAAkB5B,EAClBmB,gBACAU,uBAAwB1B,K","file":"0.9a2173a5ef629d3739fc.js","sourcesContent":["import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { RefObject } from 'react';\nimport React, { FC, useRef, useCallback } from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport useContextMenuPosition from '../../hooks/useContextMenuPosition';\n\nimport RippleEffect from './RippleEffect';\nimport Menu from './Menu';\nimport MenuItem from './MenuItem';\n\nimport './ListItem.scss';\n\ntype OnClickHandler = (e: React.MouseEvent) => void;\n\ntype MenuItemContextAction = {\n title: string;\n icon: string;\n destructive?: boolean;\n handler?: () => void;\n};\n\ntype OwnProps = {\n ref?: RefObject;\n icon?: string;\n className?: string;\n style?: string;\n children: any;\n disabled?: boolean;\n ripple?: boolean;\n narrow?: boolean;\n inactive?: boolean;\n focus?: boolean;\n destructive?: boolean;\n multiline?: boolean;\n contextActions?: MenuItemContextAction[];\n onClick?: OnClickHandler;\n};\n\nconst ListItem: FC = (props) => {\n const {\n ref,\n icon,\n className,\n style,\n children,\n disabled,\n ripple,\n narrow,\n inactive,\n focus,\n destructive,\n multiline,\n contextActions,\n onClick,\n } = props;\n\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(containerRef, !contextActions);\n\n const getTriggerElement = useCallback(() => containerRef.current, []);\n\n const getRootElement = useCallback(\n () => containerRef.current!.closest('.custom-scroll'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => containerRef.current!.querySelector('.ListItem-context-menu .bubble'),\n [],\n );\n\n const { positionX, positionY, style: menuStyle } = useContextMenuPosition(\n contextMenuPosition,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n );\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n return;\n }\n onClick(e);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (inactive || IS_TOUCH_ENV) {\n return;\n }\n if (contextActions && (e.button === 2 || !onClick)) {\n handleBeforeContextMenu(e);\n }\n if (e.button === 0) {\n if (!onClick) {\n handleContextMenu(e);\n } else {\n handleClick(e);\n }\n }\n }, [inactive, contextActions, onClick, handleBeforeContextMenu, handleContextMenu, handleClick]);\n\n const fullClassName = buildClassName(\n 'ListItem no-selection',\n className,\n ripple && 'has-ripple',\n narrow && 'narrow',\n disabled && 'disabled',\n inactive && 'inactive',\n contextMenuPosition && 'has-menu-open',\n focus && 'focus',\n destructive && 'destructive',\n multiline && 'multiline',\n );\n\n return (\n \n \n {icon && (\n \n )}\n {multiline && (
{children}
)}\n {!multiline && children}\n {!disabled && !inactive && ripple && (\n \n )}\n
\n {contextActions && contextMenuPosition !== undefined && (\n \n {contextActions.map((action) => (\n \n {action.title}\n \n ))}\n \n )}\n
\n );\n};\n\nexport default ListItem;\n","import { RefObject } from 'react';\nimport {\n useEffect, useRef, useCallback, useState,\n} from '../lib/teact/teact';\n\nimport { throttle, debounce } from '../util/schedulers';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\n\ntype TargetCallback = (entry: IntersectionObserverEntry) => void;\ntype RootCallback = (entries: IntersectionObserverEntry[]) => void;\ntype ObserveCleanup = NoneToVoidFunction;\nexport type ObserveFn = (target: HTMLElement, targetCallback?: TargetCallback) => ObserveCleanup;\n\ninterface IntersectionController {\n observer: IntersectionObserver;\n callbacks: Map;\n}\n\ninterface Response {\n observe: ObserveFn;\n freeze: NoneToVoidFunction;\n unfreeze: NoneToVoidFunction;\n}\n\nexport function useIntersectionObserver({\n rootRef,\n throttleMs,\n debounceMs,\n shouldSkipFirst,\n margin,\n threshold,\n isDisabled,\n}: {\n rootRef: RefObject;\n throttleMs?: number;\n debounceMs?: number;\n shouldSkipFirst?: boolean;\n margin?: number;\n threshold?: number | number[];\n isDisabled?: boolean;\n}, rootCallback?: RootCallback): Response {\n const controllerRef = useRef();\n const rootCallbackRef = useRef();\n const isFrozenRef = useRef();\n const onUnfreezeRef = useRef();\n\n rootCallbackRef.current = rootCallback;\n\n const freeze = useCallback(() => {\n isFrozenRef.current = true;\n }, []);\n\n const unfreeze = useCallback(() => {\n isFrozenRef.current = false;\n\n if (onUnfreezeRef.current) {\n onUnfreezeRef.current();\n onUnfreezeRef.current = undefined;\n }\n }, []);\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\n return () => {\n if (controllerRef.current) {\n controllerRef.current.observer.disconnect();\n controllerRef.current.callbacks.clear();\n controllerRef.current = undefined;\n }\n };\n }, [isDisabled]);\n\n function initController() {\n const callbacks = new Map();\n const entriesAccumulator = new Map();\n const observerCallbackSync = () => {\n const entries = Array.from(entriesAccumulator.values());\n\n entries.forEach((entry: IntersectionObserverEntry) => {\n const callback = callbacks.get(entry.target);\n if (callback) {\n callback!(entry, entries);\n }\n });\n\n if (rootCallbackRef.current) {\n rootCallbackRef.current(entries);\n }\n\n entriesAccumulator.clear();\n };\n const scheduler = throttleMs ? throttle : debounceMs ? debounce : undefined;\n const observerCallback = scheduler\n ? scheduler(observerCallbackSync, (throttleMs || debounceMs)!, !shouldSkipFirst)\n : observerCallbackSync;\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n entriesAccumulator.set(entry.target, entry);\n });\n\n if (isFrozenRef.current) {\n onUnfreezeRef.current = () => {\n observerCallback();\n };\n } else {\n observerCallback();\n }\n },\n {\n root: rootRef.current,\n rootMargin: margin ? `${margin}px` : undefined,\n threshold,\n },\n );\n\n controllerRef.current = { observer, callbacks };\n }\n\n const observe = useCallback((target, targetCallback) => {\n if (!controllerRef.current) {\n initController();\n }\n\n const controller = controllerRef.current!;\n controller.observer.observe(target);\n\n if (targetCallback) {\n controller.callbacks.set(target, targetCallback);\n }\n\n return () => {\n if (targetCallback) {\n controller.callbacks.delete(target);\n }\n\n controller.observer.unobserve(target);\n };\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isDisabled]);\n\n return { observe, freeze, unfreeze };\n}\n\nexport function useOnIntersect(\n targetRef: RefObject, observe?: ObserveFn, callback?: TargetCallback,\n) {\n useEffect(() => {\n return observe ? observe(targetRef.current!, callback) : undefined;\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n}\n\nexport function useIsIntersecting(\n targetRef: RefObject, observe?: ObserveFn, callback?: TargetCallback,\n) {\n const [isIntersecting, setIsIntersecting] = useState(!observe);\n\n useOnIntersect(targetRef, observe, (entry) => {\n setIsIntersecting(entry.isIntersecting);\n\n if (callback) {\n callback(entry);\n }\n });\n\n return isIntersecting;\n}\n","import { useEffect } from '../lib/teact/teact';\n\nimport { ApiMediaFormat } from '../api/types';\n\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (\n mediaHash: string | false | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory(mediaHash) : undefined;\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!noLoad && mediaHash && !mediaData) {\n const startedAt = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat).then(() => {\n const spentTime = Date.now() - startedAt;\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, delay]);\n\n return mediaData;\n};\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { selectChatMessages, selectUser } from '../../modules/selectors';\nimport { getUserFullName, getUserStatus, isUserOnline } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n userId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n forceShowSelf?: boolean;\n status?: string;\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n noStatusOrTyping?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n isSavedMessages?: boolean;\n areMessagesLoaded: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst PrivateChatInfo: FC = ({\n typingStatus,\n avatarSize = 'medium',\n status,\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n noStatusOrTyping,\n user,\n isSavedMessages,\n areMessagesLoaded,\n lastSyncTime,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const fullName = getUserFullName(user);\n\n useEffect(() => {\n if (withFullInfo && lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime, withFullInfo]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent, hasPhoto: boolean) => {\n if (user && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: user.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [user, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!user) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (status) {\n return (\n {status}\n );\n }\n\n if (withUpdatingStatus && !areMessagesLoaded) {\n return (\n {lang('Updating')}\n );\n }\n\n if (!user) {\n return undefined;\n }\n\n if (typingStatus) {\n return ;\n }\n\n return (\n
\n {withUsername && user.username && {user.username}}\n {getUserStatus(user, lang)}\n
\n );\n }\n\n return (\n
\n \n
\n {isSavedMessages ? (\n
\n

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {user && user.isVerified && }\n
\n )}\n {(status || (!isSavedMessages && !noStatusOrTyping)) && renderStatusOrTyping()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const areMessagesLoaded = Boolean(selectChatMessages(global, userId));\n\n return {\n lastSyncTime, user, isSavedMessages, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport trapFocus from '../../util/trapFocus';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Portal from './Portal';\n\nimport './Modal.scss';\n\nconst ANIMATION_DURATION = 200;\n\ntype OwnProps = {\n title?: string;\n className?: string;\n isOpen?: boolean;\n header?: FC;\n hasCloseButton?: boolean;\n noBackdrop?: boolean;\n children: any;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onEnter?: () => void;\n};\n\nconst Modal: FC = (props) => {\n const {\n title,\n className,\n isOpen,\n header,\n hasCloseButton,\n noBackdrop,\n children,\n onClose,\n onCloseAnimationEnd,\n onEnter,\n } = props;\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n // eslint-disable-next-line no-null/no-null\n const modalRef = useRef(null);\n\n useEffect(() => (isOpen\n ? captureKeyboardListeners({ onEsc: onClose, onEnter })\n : undefined), [isOpen, onClose, onEnter]);\n useEffect(() => (isOpen && modalRef.current ? trapFocus(modalRef.current) : undefined), [isOpen]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n document.body.classList.toggle('has-open-dialog', isOpen);\n\n if (isOpen || (!isOpen && prevIsOpen !== undefined)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n\n return () => {\n document.body.classList.remove('has-open-dialog');\n };\n }, [isOpen]);\n\n const lang = useLang();\n\n if (!shouldRender) {\n return undefined;\n }\n\n function renderHeader() {\n if (header) {\n return header;\n }\n\n if (!title) {\n return undefined;\n }\n\n return (\n
\n {hasCloseButton && (\n \n \n \n )}\n
{title}
\n
\n );\n }\n\n const fullClassName = buildClassName(\n 'Modal',\n className,\n transitionClassNames,\n noBackdrop && 'transparent-backdrop',\n );\n\n return (\n \n \n
\n
\n
\n {renderHeader()}\n
\n {children}\n
\n
\n
\n
\n
\n );\n};\n\nexport default Modal;\n","export default function trapFocus(element: HTMLElement) {\n function handleKeyDown(e: KeyboardEvent) {\n if (e.key !== 'Tab') {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n const focusableElements = Array.from(\n element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'),\n ) as HTMLElement[];\n if (!focusableElements.length) {\n return;\n }\n\n const currentFocusedIndex = focusableElements.findIndex((em) => em.isSameNode(document.activeElement));\n let newFocusedIndex = 0;\n if (currentFocusedIndex >= 0) {\n if (e.shiftKey) {\n newFocusedIndex = currentFocusedIndex > 0\n ? currentFocusedIndex - 1\n : focusableElements.length - 1;\n } else {\n newFocusedIndex = currentFocusedIndex < focusableElements.length - 1\n ? currentFocusedIndex + 1\n : 0;\n }\n }\n\n focusableElements[newFocusedIndex].focus();\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useLayoutEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Transition.scss';\n\ntype ChildrenFn = (isActive: boolean, isFrom: boolean) => any;\ntype OwnProps = {\n ref?: RefObject;\n activeKey: number;\n name: (\n 'none' | 'slide' | 'mv-slide' | 'slide-fade' | 'zoom-fade' | 'scroll-slide' | 'fade' | 'slide-layers'\n | 'push-slide' | 'reveal'\n );\n direction?: 'auto' | 'inverse' | 1 | -1;\n renderCount?: number;\n shouldRestoreHeight?: boolean;\n shouldCleanup?: boolean;\n id?: string;\n className?: string;\n onStart?: () => void;\n onStop?: () => void;\n children: ChildrenFn;\n};\n\ntype StateProps = {\n animationLevel: number;\n};\n\nconst ANIMATION_DURATION = {\n slide: 450,\n 'mv-slide': 400,\n 'slide-fade': 400,\n 'zoom-fade': 150,\n 'scroll-slide': 500,\n fade: 150,\n 'slide-layers': IS_MOBILE_SCREEN ? 450 : 300,\n 'push-slide': 300,\n reveal: 350,\n};\n\nconst CLEANED_UP = Symbol('CLEANED_UP');\n\nconst Transition: FC = ({\n ref,\n activeKey,\n name,\n direction = 'auto',\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n id,\n className,\n onStart,\n onStop,\n children,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const rendersRef = useRef>({});\n const prevActiveKey = usePrevious(activeKey);\n const activateTimeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n const activeKeyChanged = prevActiveKey !== undefined && activeKey !== prevActiveKey;\n\n if (!renderCount && activeKeyChanged) {\n rendersRef.current = { [prevActiveKey]: rendersRef.current[prevActiveKey] };\n }\n\n rendersRef.current[activeKey] = children;\n\n useLayoutEffect(() => {\n function cleanup() {\n if (!shouldCleanup) {\n return;\n }\n\n rendersRef.current = { [prevActiveKey]: CLEANED_UP };\n forceUpdate();\n }\n\n const container = containerRef.current!;\n\n const childElements = container.children;\n if (childElements.length === 1 && !activeKeyChanged) {\n childElements[0].classList.add('active');\n\n return;\n }\n\n const childNodes = Array.from(container.childNodes);\n\n if (!activeKeyChanged || !childNodes.length) {\n return;\n }\n\n if (activateTimeoutRef.current) {\n clearTimeout(activateTimeoutRef.current);\n activateTimeoutRef.current = undefined;\n }\n\n const isBackwards = (\n direction === -1\n || (direction === 'auto' && prevActiveKey > activeKey)\n || (direction === 'inverse' && prevActiveKey < activeKey)\n );\n\n container.classList.remove('animating');\n container.classList.toggle('backwards', isBackwards);\n\n const keys = Object.keys(rendersRef.current).map(Number);\n const prevActiveIndex = renderCount ? prevActiveKey : keys.indexOf(prevActiveKey);\n const activeIndex = renderCount ? activeKey : keys.indexOf(activeKey);\n\n if (name === 'none' || animationLevel === 0) {\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n cleanup();\n\n return;\n }\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('active');\n node.classList.toggle('from', i === prevActiveIndex);\n node.classList.toggle('through', (\n (i > prevActiveIndex && i < activeIndex) || (i < prevActiveIndex && i > activeIndex)\n ));\n node.classList.toggle('to', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n const width = container.offsetWidth;\n container.scrollBy({\n left: activeIndex > prevActiveIndex ? width : -width,\n behavior: 'smooth',\n });\n }\n\n if (animationLevel > 0) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n }\n\n requestAnimationFrame(() => {\n container.classList.add('animating');\n\n activateTimeoutRef.current = window.setTimeout(() => {\n requestAnimationFrame(() => {\n container.classList.remove('animating', 'backwards');\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n container.scrollLeft = activeKey * container.offsetWidth;\n }\n\n if (shouldRestoreHeight) {\n const activeElement = container.querySelector('.active');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n\n cleanup();\n\n if (onStop) {\n onStop();\n }\n });\n }, ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n\n if (onStart) {\n onStart();\n }\n });\n }, [\n activeKey,\n prevActiveKey,\n activeKeyChanged,\n direction,\n name,\n onStart,\n onStop,\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n animationLevel,\n forceUpdate,\n ]);\n\n useLayoutEffect(() => {\n if (shouldRestoreHeight) {\n const container = containerRef.current!;\n const activeElement = container.querySelector('.active')\n || container.querySelector('.from');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n }, [shouldRestoreHeight, children]);\n\n const renders = rendersRef.current;\n const collection = Object.keys(renderCount ? new Array(renderCount).fill(undefined) : renders).map(Number);\n const contents = collection.map((key) => {\n const render = renders[key];\n\n return (\n typeof render === 'function' ?
{render(key === activeKey, key === prevActiveKey)}
: undefined\n );\n });\n\n const fullClassName = buildClassName(\n 'Transition',\n className,\n animationLevel === 0 && name === 'scroll-slide' ? 'slide' : name,\n );\n\n return (\n
\n {contents}\n
\n );\n};\n\nexport default withGlobal((global) => {\n const { animationLevel } = global.settings.byKey;\n return { animationLevel };\n})(Transition);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiChat, ApiMediaFormat } from '../../api/types';\n\nimport { IS_TEST } from '../../config';\nimport {\n getChatAvatarHash, getChatTitle, isChatPrivate,\n getUserFullName, isUserOnline, isDeletedUser, getUserColorKey,\n} from '../../modules/helpers';\nimport { getFirstLetters } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useLang from '../../hooks/useLang';\n\nimport './Avatar.scss';\n\ntype OwnProps = {\n className?: string;\n size?: 'micro' | 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n withOnlineStatus?: boolean;\n chat?: ApiChat;\n user?: ApiUser;\n text?: string;\n isSavedMessages?: boolean;\n lastSyncTime?: number;\n onClick?: (e: ReactMouseEvent, hasPhoto: boolean) => void;\n};\n\nconst Avatar: FC = ({\n className,\n size = 'large',\n chat,\n user,\n text,\n withOnlineStatus,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const isDeleted = user && isDeletedUser(user);\n let imageHash: string | undefined;\n\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n imageHash = getChatAvatarHash(user);\n } else if (chat) {\n imageHash = getChatAvatarHash(chat);\n }\n }\n\n const dataUri = useMedia(imageHash, false, ApiMediaFormat.DataUri, lastSyncTime);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(dataUri, 'slow');\n\n useLang();\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = ;\n } else if (isDeleted) {\n content = ;\n } else if (shouldRenderFullMedia) {\n content = \"\";\n } else if (user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (chat) {\n const title = getChatTitle(chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else if (text) {\n content = getFirstLetters(text, 2);\n }\n\n const isOnline = !isSavedMessages && user && isUserOnline(user);\n const fullClassName = buildClassName(\n `Avatar size-${size}`,\n className,\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n withOnlineStatus && isOnline && 'online',\n onClick && 'interactive',\n (!isSavedMessages && !shouldRenderFullMedia) && 'no-photo',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (onClick) {\n onClick(e, isSavedMessages || shouldRenderFullMedia);\n }\n }, [onClick, isSavedMessages, shouldRenderFullMedia]);\n\n const senderId = (user || chat) && (user || chat)!.id;\n\n return (\n
\n {typeof content === 'string' ? renderText(content, [size === 'jumbo' ? 'hq_emoji' : 'emoji']) : content}\n
\n );\n};\n\nexport default memo(Avatar);\n","import { RefObject, UIEvent } from 'react';\nimport { LoadMoreDirection } from '../../types';\n\nimport React, {\n FC, useCallback, useEffect, useLayoutEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport resetScroll from '../../util/resetScroll';\n\ntype OwnProps = {\n ref?: RefObject;\n className?: string;\n onLoadMore?: ({ direction }: { direction: LoadMoreDirection }) => void;\n onScroll?: (e: UIEvent) => void;\n items?: any[];\n itemSelector?: string;\n preloadBackwards?: number;\n sensitiveArea?: number;\n noScrollRestore?: boolean;\n noFastList?: boolean;\n cacheBuster?: any;\n children: any;\n};\n\nconst DEFAULT_LIST_SELECTOR = '.ListItem';\nconst DEFAULT_PRELOAD_BACKWARDS = 20;\nconst DEFAULT_SENSITIVE_AREA = 800;\n\nconst InfiniteScroll: FC = ({\n ref,\n className,\n onLoadMore,\n onScroll,\n items,\n itemSelector = DEFAULT_LIST_SELECTOR,\n preloadBackwards = DEFAULT_PRELOAD_BACKWARDS,\n sensitiveArea = DEFAULT_SENSITIVE_AREA,\n // Used to turn off restoring scroll position (e.g. for frequently re-ordered chat or user lists)\n noScrollRestore = false,\n noFastList,\n // Used to re-query `listItemElements` if rendering is delayed by transition\n cacheBuster,\n children,\n}: OwnProps) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef(null);\n if (ref) {\n containerRef = ref;\n }\n\n const stateRef = useRef<{\n listItemElements: NodeListOf;\n isScrollTopJustUpdated: boolean;\n currentAnchor: HTMLDivElement | undefined;\n currentAnchorTop: number;\n }>({} as any);\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(() => {\n if (!onLoadMore) {\n return [];\n }\n\n return [\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [onLoadMore, items]);\n\n // Initial preload\n useEffect(() => {\n if (!loadMoreBackwards) {\n return;\n }\n\n if (preloadBackwards > 0 && (!items || items.length < preloadBackwards)) {\n loadMoreBackwards();\n return;\n }\n\n const { scrollHeight, clientHeight } = containerRef.current!;\n if (clientHeight && scrollHeight <= clientHeight) {\n loadMoreBackwards();\n }\n }, [items, loadMoreBackwards, preloadBackwards]);\n\n // Restore `scrollTop` after adding items\n useLayoutEffect(() => {\n const container = containerRef.current!;\n const state = stateRef.current;\n\n state.listItemElements = container.querySelectorAll(itemSelector);\n\n if (noScrollRestore) {\n return;\n }\n\n let newScrollTop;\n\n if (state.currentAnchor && Array.from(state.listItemElements).includes(state.currentAnchor)) {\n const { scrollTop } = container;\n const newAnchorTop = state.currentAnchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - state.currentAnchorTop);\n } else {\n const nextAnchor = state.listItemElements[0];\n if (nextAnchor && nextAnchor.offsetParent) {\n state.currentAnchor = nextAnchor;\n state.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n\n resetScroll(container, newScrollTop);\n\n state.isScrollTopJustUpdated = true;\n }, [noScrollRestore, itemSelector, items, cacheBuster]);\n\n const handleScroll = useCallback((e: UIEvent) => {\n if (loadMoreForwards && loadMoreBackwards) {\n const {\n listItemElements, isScrollTopJustUpdated, currentAnchor, currentAnchorTop,\n } = stateRef.current;\n\n if (isScrollTopJustUpdated) {\n stateRef.current.isScrollTopJustUpdated = false;\n return;\n }\n\n const listLength = listItemElements.length;\n const container = containerRef.current!;\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const top = listLength ? listItemElements[0].offsetTop : 0;\n const isNearTop = scrollTop <= top + sensitiveArea;\n const bottom = listLength\n ? listItemElements[listLength - 1].offsetTop + listItemElements[listLength - 1].offsetHeight\n : scrollHeight;\n const isNearBottom = bottom - (scrollTop + offsetHeight) <= sensitiveArea;\n let isUpdated = false;\n\n if (isNearTop) {\n const nextAnchor = listItemElements[0];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingUp = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop > currentAnchorTop\n );\n\n if (isMovingUp) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreForwards();\n }\n }\n }\n\n if (isNearBottom) {\n const nextAnchor = listItemElements[listLength - 1];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingDown = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop < currentAnchorTop\n );\n\n if (isMovingDown) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreBackwards();\n }\n }\n }\n\n if (!isUpdated) {\n if (currentAnchor && currentAnchor.offsetParent) {\n stateRef.current.currentAnchorTop = currentAnchor.getBoundingClientRect().top;\n } else {\n const nextAnchor = listItemElements[0];\n\n if (nextAnchor) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n }\n }\n\n if (onScroll) {\n onScroll(e);\n }\n }, [loadMoreBackwards, loadMoreForwards, onScroll, sensitiveArea]);\n\n return (\n
\n {children}\n
\n );\n};\n\nexport default InfiniteScroll;\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import { useEffect, useRef, useState } from '../lib/teact/teact';\n\nimport useShowTransition from './useShowTransition';\n\nconst SPEED = {\n fast: 200,\n slow: 350,\n};\n\nexport default (mediaData?: any, speed: keyof typeof SPEED = 'fast', noAnimate = false) => {\n const isMediaLoaded = Boolean(mediaData);\n const willAnimate = !useRef(isMediaLoaded).current && !noAnimate;\n const [shouldRenderThumb, setShouldRenderThumb] = useState(!isMediaLoaded);\n\n const {\n shouldRender: shouldRenderFullMedia,\n transitionClassNames,\n } = useShowTransition(isMediaLoaded, undefined, !willAnimate, speed);\n\n useEffect(() => {\n if (shouldRenderFullMedia) {\n if (willAnimate) {\n setTimeout(() => {\n setShouldRenderThumb(false);\n }, SPEED[speed]);\n } else {\n setShouldRenderThumb(false);\n }\n }\n }, [willAnimate, shouldRenderFullMedia, speed]);\n\n return {\n shouldRenderThumb,\n shouldRenderFullMedia,\n transitionClassNames,\n };\n};\n","import { ApiPhoto, ApiVideo, ApiSticker } from '../../../api/types';\nimport { getPhotoInlineDimensions, getVideoDimensions, IDimensions } from '../../../modules/helpers';\nimport windowSize from '../../../util/windowSize';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { STICKER_SIZE_INLINE_DESKTOP_FACTOR, STICKER_SIZE_INLINE_MOBILE_FACTOR } from '../../../config';\n\nexport const MEDIA_VIEWER_MEDIA_QUERY = '(max-height: 640px)';\nexport const REM = parseInt(getComputedStyle(document.documentElement).fontSize, 10);\nexport const ROUND_VIDEO_DIMENSIONS = 200;\nexport const AVATAR_FULL_DIMENSIONS = { width: 640, height: 640 };\n\nconst DEFAULT_MEDIA_DIMENSIONS: IDimensions = { width: 100, height: 100 };\nconst LIKE_STICKER_ID = '1258816259753933';\nconst MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH = 0.69;\n\nlet cachedMaxWidth: number | undefined;\n\nfunction getMaxMessageWidthRem(fromOwnMessage: boolean) {\n const regularMaxWidth = fromOwnMessage ? 30 : 29;\n if (!IS_MOBILE_SCREEN) {\n return regularMaxWidth;\n }\n\n // @optimization Limitation: changing device screen width not supported\n if (!cachedMaxWidth) {\n cachedMaxWidth = Math.min(\n regularMaxWidth,\n Math.floor(window.innerWidth * MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH) / REM,\n );\n }\n\n return cachedMaxWidth;\n}\n\nfunction getAvailableWidth(\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const extraPaddingRem = isForwarded || isWebPagePhoto ? 1.625 : 0;\n const availableWidthRem = getMaxMessageWidthRem(fromOwnMessage) - extraPaddingRem;\n\n return availableWidthRem * REM;\n}\n\nfunction getAvailableHeight(isGif?: boolean, aspectRatio?: number) {\n if (\n isGif && aspectRatio\n && aspectRatio >= 0.75 && aspectRatio <= 1.25\n ) {\n return 20 * REM;\n }\n\n return 27 * REM;\n}\n\nfunction calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n isGif,\n}: {\n width: number;\n height: number;\n fromOwnMessage: boolean;\n isForwarded?: boolean;\n isWebPagePhoto?: boolean;\n isGif?: boolean;\n}): IDimensions {\n const aspectRatio = height / width;\n const availableWidth = getAvailableWidth(fromOwnMessage, isForwarded, isWebPagePhoto);\n const availableHeight = getAvailableHeight(isGif, aspectRatio);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function getMediaViewerAvailableDimensions(withFooter: boolean, isVideo: boolean): IDimensions {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n const { width: windowWidth, height: windowHeight } = windowSize.get();\n let occupiedHeightRem = isVideo && mql.matches ? 10 : 8.25;\n if (withFooter) {\n occupiedHeightRem = mql.matches ? 10 : 15;\n }\n\n return {\n width: windowWidth,\n height: windowHeight - occupiedHeightRem * REM,\n };\n}\n\nexport function calculateInlineImageDimensions(\n photo: ApiPhoto,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const { width, height } = getPhotoInlineDimensions(photo) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n });\n}\n\nexport function calculateVideoDimensions(\n video: ApiVideo,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n) {\n const { width, height } = getVideoDimensions(video) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isGif: video.isGif,\n });\n}\n\nexport function getPictogramDimensions(): IDimensions {\n return {\n width: 2 * REM,\n height: 2 * REM,\n };\n}\n\nexport function getDocumentThumbnailDimensions(smaller?: boolean): IDimensions {\n if (smaller) {\n return {\n width: 3 * REM,\n height: 3 * REM,\n };\n }\n\n return {\n width: 3.375 * REM,\n height: 3.375 * REM,\n };\n}\n\nexport function getStickerDimensions(sticker: ApiSticker): IDimensions {\n const { width } = sticker;\n let { height } = sticker;\n\n // For some reason this sticker has some weird `height` value\n if (sticker.id === LIKE_STICKER_ID) {\n height = width;\n }\n\n const aspectRatio = (height && width) && height / width;\n const baseWidth = (IS_MOBILE_SCREEN ? STICKER_SIZE_INLINE_MOBILE_FACTOR : STICKER_SIZE_INLINE_DESKTOP_FACTOR) * REM;\n const calculatedHeight = aspectRatio ? baseWidth * aspectRatio : baseWidth;\n\n if (aspectRatio && calculatedHeight > baseWidth) {\n return {\n width: Math.round(baseWidth / aspectRatio),\n height: baseWidth,\n };\n }\n\n return {\n width: baseWidth,\n height: calculatedHeight,\n };\n}\n\nexport function calculateMediaViewerDimensions(\n { width, height }: IDimensions, withFooter: boolean, isVideo: boolean = false,\n): IDimensions {\n const { width: availableWidth, height: availableHeight } = getMediaViewerAvailableDimensions(withFooter, isVideo);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function calculateDimensions(\n availableWidth: number,\n availableHeight: number,\n mediaWidth: number,\n mediaHeight: number,\n): IDimensions {\n const aspectRatio = mediaHeight / mediaWidth;\n const calculatedWidth = Math.min(mediaWidth, availableWidth);\n const calculatedHeight = Math.round(calculatedWidth * aspectRatio);\n\n if (calculatedHeight > availableHeight) {\n return {\n width: Math.round(availableHeight / aspectRatio),\n height: availableHeight,\n };\n }\n\n return {\n width: calculatedWidth,\n height: Math.round(calculatedWidth * aspectRatio),\n };\n}\n","import React, {\n FC, useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_IOS } from '../../util/environment';\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\ntype OwnProps = {\n className?: string;\n id: string;\n animationData: AnyLiteral;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n onLoad?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise;\nlet RLottie: RLottieClass;\n\n// Time supposed for judges to measure \"Transferred Size\" in Dev Tools\nconst LOTTIE_LOAD_DELAY = 5000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC = ({\n className,\n id,\n animationData,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n onLoad,\n}) => {\n const [animation, setAnimation] = useState();\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !animationData) {\n return;\n }\n\n const exec = () => {\n if (!container.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n id,\n container.current,\n animationData,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (container.current) {\n exec();\n }\n });\n });\n }\n }, [animation, animationData, id, isLowPriority, noLoop, onLoad, quality, size, speed]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else if (shouldRestart) {\n animation.goToAndPlay(0);\n } else {\n animation.play();\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation();\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n const fullClassName = buildClassName(\n 'AnimatedSticker',\n className,\n // Workaround for an iOS bug when animated stickers sometimes disappear\n IS_IOS && play && 'is-playing',\n );\n\n const style = size ? `width: ${size}px; height: ${size}px;` : undefined;\n\n return (\n \n );\n};\n\nexport default memo(AnimatedSticker);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\nimport { TextPart } from '../common/helpers/renderMessageText';\n\nimport Modal from './Modal';\nimport Button from './Button';\n\ntype OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n header?: FC;\n textParts?: TextPart[];\n text?: string;\n confirmLabel?: string;\n confirmHandler: () => void;\n confirmIsDestructive?: boolean;\n isButtonsInOneRow?: boolean;\n};\n\nconst ConfirmDialog: FC = ({\n isOpen,\n onClose,\n onCloseAnimationEnd,\n header,\n text,\n textParts,\n confirmLabel = 'Confirm',\n confirmHandler,\n confirmIsDestructive,\n isButtonsInOneRow,\n}) => {\n const lang = useLang();\n\n return (\n \n {text && text.split('\\\\n').map((textPart) => (\n

{textPart}

\n ))}\n {textParts}\n
\n \n {confirmLabel}\n \n \n
\n \n );\n};\n\nexport default memo(ConfirmDialog);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\n\nimport './NothingFound.scss';\n\ninterface OwnProps {\n text?: string;\n}\n\nconst DEFAULT_TEXT = 'Nothing found.';\n\nconst NothingFound: FC = ({ text = DEFAULT_TEXT }) => {\n const { transitionClassNames } = useShowTransition(true);\n\n return (\n
\n {text}\n
\n );\n};\n\nexport default memo(NothingFound);\n","import { useEffect, useRef } from '../../../lib/teact/teact';\n\nimport useOnChange from '../../../hooks/useOnChange';\nimport useForceUpdate from '../../../hooks/useForceUpdate';\n\nexport default function useAsyncRendering(dependencies: T, delay?: number) {\n const isDisabled = delay === undefined;\n const shouldRenderRef = useRef(isDisabled);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n if (isDisabled) {\n return;\n }\n\n shouldRenderRef.current = false;\n\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n }, dependencies);\n\n useEffect(() => {\n if (isDisabled || shouldRenderRef.current) {\n return;\n }\n\n const exec = () => {\n shouldRenderRef.current = true;\n forceUpdate();\n };\n\n if (delay! > 0) {\n timeoutRef.current = window.setTimeout(exec, delay);\n } else {\n exec();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n\n return shouldRenderRef.current;\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({ children, className, onClick }) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","import {\n useEffect, useMemo, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { IS_PROGRESSIVE_SUPPORTED } from '../util/environment';\nimport { ApiMediaFormat } from '../api/types';\nimport { throttle } from '../util/schedulers';\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nconst STREAMING_PROGRESS = 0.75;\nconst STREAMING_TIMEOUT = 1500;\nconst PROGRESS_THROTTLE = 500;\n\nexport default (\n mediaHash: string | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory(mediaHash) : undefined;\n const isStreaming = mediaFormat === ApiMediaFormat.Stream || (\n IS_PROGRESSIVE_SUPPORTED && mediaFormat === ApiMediaFormat.Progressive\n );\n const forceUpdate = useForceUpdate();\n const [downloadProgress, setDownloadProgress] = useState(mediaData && !isStreaming ? 1 : 0);\n const startedAtRef = useRef();\n\n const handleProgress = useMemo(() => {\n return throttle((progress: number) => {\n if (!delay || (Date.now() - startedAtRef.current! > delay)) {\n setDownloadProgress(progress);\n }\n }, PROGRESS_THROTTLE, true);\n }, [delay]);\n\n useEffect(() => {\n if (!noLoad && mediaHash) {\n if (!mediaData) {\n setDownloadProgress(0);\n\n if (startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n }\n\n startedAtRef.current = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat, handleProgress).then(() => {\n const spentTime = Date.now() - startedAtRef.current!;\n startedAtRef.current = undefined;\n\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n } else if (isStreaming) {\n setTimeout(() => {\n setDownloadProgress(STREAMING_PROGRESS);\n }, STREAMING_TIMEOUT);\n }\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, isStreaming, delay, handleProgress]);\n\n useEffect(() => {\n if (noLoad && startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n setDownloadProgress(0);\n }\n }, [handleProgress, noLoad]);\n\n return { mediaData, downloadProgress };\n};\n","import React, {\n FC, useEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './ProgressSpinner.scss';\n\nconst RADIUSES = {\n s: 22, m: 25, l: 28, xl: 20,\n};\nconst STROKE_WIDTH = 2;\nconst MIN_PROGRESS = 0.05;\nconst MAX_PROGRESS = 1;\n\nconst ProgressSpinner: FC<{\n progress?: number;\n size?: 's' | 'm' | 'l' | 'xl';\n square?: boolean;\n transparent?: boolean;\n noCross?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n}> = ({\n progress = 0,\n size = 'l',\n square,\n transparent,\n noCross,\n onClick,\n}) => {\n const radius = RADIUSES[size];\n const circleRadius = radius - STROKE_WIDTH * 2;\n const borderRadius = radius - 1;\n const circumference = circleRadius * 2 * Math.PI;\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n\n useEffect(() => {\n if (!container.current) {\n return;\n }\n\n const svg = container.current.firstElementChild;\n const strokeDashOffset = circumference - Math.min(Math.max(MIN_PROGRESS, progress), MAX_PROGRESS) * circumference;\n\n if (!svg) {\n container.current.innerHTML = `\n \n `;\n } else {\n (svg.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n }, [container, circumference, borderRadius, circleRadius, progress]);\n\n const className = buildClassName(\n `ProgressSpinner size-${size}`,\n transparent && 'transparent',\n square && 'square',\n noCross && 'no-cross',\n );\n\n return (\n \n );\n};\n\nexport default memo(ProgressSpinner);\n","import { FC, useRef, useLayoutEffect } from '../../lib/teact/teact';\nimport TeactDOM from '../../lib/teact/teact-dom';\n\ntype OwnProps = {\n containerId?: string;\n className?: string;\n children: any;\n};\n\nconst Portal: FC = ({ containerId, className, children }) => {\n const elementRef = useRef(document.createElement('div'));\n\n useLayoutEffect(() => {\n const container = document.querySelector(containerId || '#portals');\n if (!container) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (className) {\n element.classList.add(className);\n }\n\n container.appendChild(element);\n\n return () => {\n TeactDOM.render(undefined, element);\n container.removeChild(element);\n };\n }, [className, containerId]);\n\n return TeactDOM.render(children, elementRef.current);\n};\n\nexport default Portal;\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport {\n getChatTypeString,\n getChatTitle,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport { selectChat, selectChatMessages, selectChatOnlineCount } from '../../modules/selectors';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n chatId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'small' | 'medium' | 'large' | 'jumbo';\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n withChatType?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n onlineCount?: number;\n areMessagesLoaded: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst GroupChatInfo: FC = ({\n typingStatus,\n avatarSize = 'medium',\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n withChatType,\n chat,\n onlineCount,\n areMessagesLoaded,\n lastSyncTime,\n loadFullChat,\n openMediaViewer,\n}) => {\n const isSuperGroup = chat && isChatSuperGroup(chat);\n const { id: chatId, isMin, isRestricted } = chat || {};\n\n useEffect(() => {\n if (chatId && !isMin && withFullInfo && lastSyncTime) {\n loadFullChat({ chatId });\n }\n }, [chatId, isMin, lastSyncTime, withFullInfo, loadFullChat, isSuperGroup]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent, hasPhoto: boolean) => {\n if (chat && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: chat.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [chat, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (withUpdatingStatus && !areMessagesLoaded && !isRestricted) {\n return (\n {lang('Updating')}\n );\n }\n\n if (!chat) {\n return undefined;\n }\n\n if (typingStatus) {\n return ;\n }\n\n if (withChatType) {\n return (\n
{lang(getChatTypeString(chat))}
\n );\n }\n\n const handle = withUsername ? chat.username : undefined;\n const groupStatus = getGroupStatus(chat, lang);\n const onlineStatus = onlineCount ? `, ${lang('OnlineCount', onlineCount, 'i')}` : undefined;\n\n return (\n
\n {handle && {handle}}\n {groupStatus}\n {onlineStatus && {onlineStatus}}\n
\n );\n }\n\n return (\n
\n \n
\n
\n

{renderText(getChatTitle(chat))}

\n {chat.isVerified && }\n
\n {renderStatusOrTyping()}\n
\n
\n );\n};\n\nfunction getGroupStatus(chat: ApiChat, lang: LangFn) {\n const chatTypeString = lang(getChatTypeString(chat));\n const { membersCount } = chat;\n\n if (chat.isRestricted) {\n return chatTypeString === 'Channel' ? 'channel is inaccessible' : 'group is inaccessible';\n }\n\n if (!membersCount) {\n return chatTypeString;\n }\n\n return chatTypeString === 'Channel'\n ? lang('Subscribers', membersCount, 'i')\n : lang('Members', membersCount, 'i');\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const { lastSyncTime } = global;\n const chat = selectChat(global, chatId);\n const onlineCount = chat ? selectChatOnlineCount(global, chat) : undefined;\n const areMessagesLoaded = Boolean(selectChatMessages(global, chatId));\n\n return {\n lastSyncTime, chat, onlineCount, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullChat', 'openMediaViewer']),\n)(GroupChatInfo));\n","import { FocusDirection } from '../types';\n\nimport { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck';\nimport { fastRaf } from './schedulers';\nimport { animateSingle } from './animation';\n\nconst MAX_DISTANCE = 1500;\nconst MIN_JS_DURATION = 250;\nconst MAX_JS_DURATION = 600;\n\nlet isAnimating = false;\n\nexport default function fastSmoothScroll(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n maxDistance = MAX_DISTANCE,\n forceDirection?: FocusDirection,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n if (forceDirection === FocusDirection.Static) {\n element.scrollIntoView({ block: position });\n\n return;\n }\n\n const { offsetTop } = element;\n\n if (forceDirection === undefined) {\n const offset = offsetTop - container.scrollTop;\n\n if (offset < -maxDistance) {\n container.scrollTop += (offset + maxDistance);\n } else if (offset > maxDistance) {\n container.scrollTop += (offset - maxDistance);\n }\n } else if (forceDirection === FocusDirection.Up) {\n container.scrollTop = offsetTop + maxDistance;\n } else if (forceDirection === FocusDirection.Down) {\n container.scrollTop = Math.max(0, offsetTop - maxDistance);\n }\n\n isAnimating = true;\n fastRaf(() => {\n dispatchHeavyAnimationEvent(MAX_JS_DURATION);\n scrollWithJs(container, element, position, margin, forceDuration, forceCurrentContainerHeight);\n });\n}\n\nexport function isAnimatingScroll() {\n return isAnimating;\n}\n\nfunction scrollWithJs(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n const { offsetTop: elementTop, offsetHeight: elementHeight } = element;\n const { scrollTop, offsetHeight: containerHeight, scrollHeight } = container;\n const targetContainerHeight = !forceCurrentContainerHeight && container.dataset.normalHeight\n ? Number(container.dataset.normalHeight)\n : containerHeight;\n\n let path!: number;\n\n switch (position) {\n case 'start':\n path = (elementTop - margin) - scrollTop;\n break;\n case 'end':\n path = (elementTop + elementHeight + margin) - (scrollTop + targetContainerHeight);\n break;\n // 'nearest' is not supported yet\n case 'nearest':\n case 'center':\n path = elementHeight < targetContainerHeight\n ? (elementTop + elementHeight / 2) - (scrollTop + targetContainerHeight / 2)\n : (elementTop - margin) - scrollTop;\n break;\n }\n\n if (path < 0) {\n const remainingPath = -scrollTop;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollHeight - (scrollTop + targetContainerHeight);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollTop + path;\n const duration = forceDuration || (\n MIN_JS_DURATION + (Math.abs(path) / MAX_DISTANCE) * (MAX_JS_DURATION - MIN_JS_DURATION)\n );\n const startAt = Date.now();\n\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / duration, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollTop = Math.round(target - currentPath);\n\n isAnimating = t < 1;\n\n return isAnimating;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport Spinner from './Spinner';\n\nimport './Radio.scss';\n\ntype OwnProps = {\n id?: string;\n name: string;\n label: string;\n subLabel?: string;\n value: string;\n checked: boolean;\n disabled?: boolean;\n hidden?: boolean;\n isLoading?: boolean;\n onChange: (e: ChangeEvent) => void;\n};\n\nconst Radio: FC = ({\n id,\n label,\n subLabel,\n value,\n name,\n checked,\n disabled,\n hidden,\n isLoading,\n onChange,\n}) => {\n const className = buildClassName(\n 'Radio',\n disabled && 'disabled',\n hidden && 'hidden-widget',\n isLoading && 'loading',\n );\n\n return (\n \n );\n};\n\nexport default memo(Radio);\n","import { ChangeEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport Radio from './Radio';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n hidden?: boolean;\n};\n\ntype OwnProps = {\n id?: string;\n name: string;\n options: IRadioOption[];\n selected?: string;\n disabled?: boolean;\n loadingOption?: string;\n onChange: (value: string) => void;\n};\n\nconst RadioGroup: FC = ({\n id,\n name,\n options,\n selected,\n disabled,\n loadingOption,\n onChange,\n}) => {\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value } = event.currentTarget;\n onChange(value);\n }, [onChange]);\n\n return (\n
\n {options.map((option) => (\n
\n );\n};\n\nexport default memo(RadioGroup);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\nimport { LoadMoreDirection } from '../types';\n\nimport { areSortedArraysEqual } from '../util/iteratees';\nimport useForceUpdate from './useForceUpdate';\nimport usePrevious from './usePrevious';\n\ntype GetMore = (args: { direction: LoadMoreDirection }) => void;\ntype LoadMoreBackwards = (args: { offsetId?: number }) => void;\n\nconst DEFAULT_LIST_SLICE = 30;\n\nexport default (\n loadMoreBackwards?: LoadMoreBackwards,\n listIds?: number[],\n isDisabled = false,\n listSlice = DEFAULT_LIST_SLICE,\n forceFullPreload = false,\n): [number[]?, GetMore?] => {\n const lastParamsRef = useRef<{\n direction?: LoadMoreDirection;\n offsetId?: number;\n }>();\n\n const viewportIdsRef = useRef((() => {\n // Only run once to initialize\n if (!listIds || lastParamsRef.current) {\n return undefined;\n }\n\n const { newViewportIds } = getViewportSlice(listIds, listIds[0], LoadMoreDirection.Forwards, listSlice);\n return newViewportIds;\n })());\n\n const forceUpdate = useForceUpdate();\n\n const prevListIds = usePrevious(listIds);\n const prevIsDisabled = usePrevious(isDisabled);\n if (listIds && !isDisabled && (listIds !== prevListIds || isDisabled !== prevIsDisabled)) {\n const { offsetId = listIds[0], direction = LoadMoreDirection.Forwards } = lastParamsRef.current || {};\n const { newViewportIds } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (!viewportIdsRef.current || !areSortedArraysEqual(viewportIdsRef.current, newViewportIds)) {\n viewportIdsRef.current = newViewportIds;\n }\n }\n\n useEffect(() => {\n if (listIds && !isDisabled && loadMoreBackwards && forceFullPreload) {\n const viewportIds = viewportIdsRef.current!;\n loadMoreBackwards({ offsetId: viewportIds[viewportIds.length - 1] });\n }\n }, [listIds, isDisabled, loadMoreBackwards, forceFullPreload]);\n\n const getMore: GetMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n const viewportIds = viewportIdsRef.current;\n\n const offsetId = viewportIds\n ? direction === LoadMoreDirection.Backwards ? viewportIds[viewportIds.length - 1] : viewportIds[0]\n : undefined;\n\n if (!listIds) {\n if (loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n\n return;\n }\n\n lastParamsRef.current = { ...lastParamsRef.current, direction, offsetId };\n\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (areSomeLocal && !(viewportIds && areSortedArraysEqual(viewportIds, newViewportIds))) {\n viewportIdsRef.current = newViewportIds;\n forceUpdate();\n }\n\n if (!areAllLocal && loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n }, [listIds, listSlice, loadMoreBackwards, forceUpdate]);\n\n return isDisabled ? [listIds] : [viewportIdsRef.current, getMore];\n};\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId = 0,\n direction: LoadMoreDirection,\n listSlice: number,\n) {\n const { length } = sourceIds;\n const index = sourceIds.indexOf(offsetId);\n const isForwards = direction === LoadMoreDirection.Forwards;\n const indexForDirection = isForwards ? index : (index + 1) || length;\n const from = Math.max(0, indexForDirection - listSlice);\n const to = indexForDirection + listSlice - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { STICKER_SIZE_TWO_FA } from '../../config';\nimport { getStickerDimensions } from './helpers/mediaDimensions';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './AnimatedEmoji.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n observeIntersection?: ObserveFn;\n isInline?: boolean;\n lastSyncTime?: number;\n};\n\nconst QUALITY = 1;\nconst RESIZE_FACTOR = 0.5;\n\nconst AnimatedEmoji: FC = ({\n sticker, isInline = false, observeIntersection, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isAnimationLoaded, markAnimationLoaded] = useFlag();\n const localMediaHash = `sticker${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl, lastSyncTime);\n const { transitionClassNames } = useTransitionForMedia(previewBlobUrl, 'slow');\n\n const mediaData = useMedia(localMediaHash, !isIntersecting, ApiMediaFormat.Lottie, lastSyncTime);\n const isMediaLoaded = Boolean(mediaData);\n\n const [playKey, setPlayKey] = useState(String(Math.random()));\n const handleClick = useCallback(() => {\n setPlayKey(String(Math.random()));\n }, []);\n\n let width: number;\n if (isInline) {\n width = getStickerDimensions(sticker).width * RESIZE_FACTOR;\n } else {\n width = STICKER_SIZE_TWO_FA;\n }\n\n const style = `width: ${width}px; height: ${width}px;`;\n\n return (\n \n {previewBlobUrl && !isAnimationLoaded && (\n \"\"\n )}\n {isMediaLoaded && (\n \n )}\n
\n );\n};\n\nexport default AnimatedEmoji;\n","import { useEffect } from '../lib/teact/teact';\n\nexport default (\n onBlur: AnyToVoidFunction,\n onFocus: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (!document.hasFocus()) {\n onBlur();\n }\n\n window.addEventListener('blur', onBlur);\n window.addEventListener('focus', onFocus);\n\n return () => {\n window.removeEventListener('focus', onFocus);\n window.removeEventListener('blur', onBlur);\n };\n }, [onBlur, onFocus]);\n};\n","export enum SwipeDirection {\n Up,\n Down,\n Left,\n Right,\n}\n\ninterface CaptureOptions {\n onCapture?: (e: MouseEvent | TouchEvent) => void;\n onRelease?: (e: MouseEvent | TouchEvent) => void;\n onDrag?: (\n e: MouseEvent | TouchEvent,\n captureEvent: MouseEvent | TouchEvent,\n params: {\n dragOffsetX: number;\n dragOffsetY: number;\n },\n ) => void;\n onSwipe?: (e: Event, direction: SwipeDirection) => void;\n onClick?: (e: MouseEvent | TouchEvent) => void;\n excludedClosestSelector?: string;\n withCursor?: boolean;\n}\n\n// https://stackoverflow.com/questions/11287877/how-can-i-get-e-offsetx-on-mobile-ipad\n// Android does not have this value, and iOS has it but as read-only\nexport interface RealTouchEvent extends TouchEvent {\n pageX?: number;\n pageY?: number;\n}\n\nconst MOVED_THRESHOLD = 15;\nconst SWIPE_THRESHOLD = 50;\n\nexport function captureEvents(element: HTMLElement, options: CaptureOptions) {\n let captureEvent: MouseEvent | RealTouchEvent | undefined;\n let hasMoved = false;\n\n function onCapture(e: MouseEvent | RealTouchEvent) {\n if (options.excludedClosestSelector && (\n (e.target as HTMLElement).matches(options.excludedClosestSelector)\n || (e.target as HTMLElement).closest(options.excludedClosestSelector)\n )) {\n return;\n }\n\n captureEvent = e;\n\n if (e.type === 'mousedown') {\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onRelease);\n } else if (e.type === 'touchstart') {\n document.addEventListener('touchmove', onMove);\n document.addEventListener('touchend', onRelease);\n document.addEventListener('touchcancel', onRelease);\n\n if ('touches' in e) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n }\n\n document.body.classList.add('no-selection');\n if (options.withCursor) {\n document.body.classList.add('cursor-grabbing');\n }\n\n if (options.onCapture) {\n options.onCapture(e);\n }\n }\n\n function onRelease(e: MouseEvent | TouchEvent) {\n if (captureEvent) {\n if (options.withCursor) {\n document.body.classList.remove('cursor-grabbing');\n }\n document.body.classList.remove('no-selection');\n\n document.removeEventListener('mouseup', onRelease);\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('touchcancel', onRelease);\n document.removeEventListener('touchend', onRelease);\n document.removeEventListener('touchmove', onMove);\n\n captureEvent = undefined;\n\n if (hasMoved) {\n if (options.onRelease) {\n options.onRelease(e);\n }\n } else if (options.onClick) {\n options.onClick(e);\n }\n }\n\n hasMoved = false;\n }\n\n function onMove(e: MouseEvent | RealTouchEvent) {\n if (captureEvent) {\n if (e.type === 'touchmove' && ('touches' in e)) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n\n const dragOffsetX = e.pageX! - captureEvent.pageX!;\n const dragOffsetY = e.pageY! - captureEvent.pageY!;\n\n if (Math.abs(dragOffsetX) >= MOVED_THRESHOLD || Math.abs(dragOffsetY) >= MOVED_THRESHOLD) {\n hasMoved = true;\n }\n\n if (options.onDrag) {\n options.onDrag(e, captureEvent, { dragOffsetX, dragOffsetY });\n }\n\n if (options.onSwipe) {\n processSwipe(e, dragOffsetX, dragOffsetY, options.onSwipe);\n }\n }\n }\n\n element.addEventListener('mousedown', onCapture);\n element.addEventListener('touchstart', onCapture, { passive: true });\n\n return () => {\n element.removeEventListener('mousedown', onCapture);\n element.removeEventListener('touchstart', onCapture);\n };\n}\n\nfunction processSwipe(\n e: Event, dragOffsetX: number, dragOffsetY: number, onSwipe: (e: Event, direction: SwipeDirection) => void,\n) {\n const xAbs = Math.abs(dragOffsetX);\n const yAbs = Math.abs(dragOffsetY);\n\n if (dragOffsetX && dragOffsetY) {\n const ratio = Math.max(xAbs, yAbs) / Math.min(xAbs, yAbs);\n // Diagonal swipe\n if (ratio < 2) {\n return;\n }\n }\n\n if (xAbs >= SWIPE_THRESHOLD) {\n if (dragOffsetX < 0) {\n onSwipe(e, SwipeDirection.Left);\n } else {\n onSwipe(e, SwipeDirection.Right);\n }\n } else if (yAbs >= SWIPE_THRESHOLD) {\n if (dragOffsetY < 0) {\n onSwipe(e, SwipeDirection.Up);\n } else {\n onSwipe(e, SwipeDirection.Down);\n }\n }\n}\n","import React, { FC } from '../../lib/teact/teact';\n\nimport './VerifiedIcon.scss';\n\nconst VerifiedIcon: FC = () => {\n return (\n \n );\n};\n\nexport default VerifiedIcon;\n","import { DEBUG } from '../config';\n\nexport default (mediaEl: HTMLMediaElement) => {\n mediaEl.play().catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n });\n};\n","import React, { useCallback, useMemo, useState } from '../lib/teact/teact';\nimport { debounce } from '../util/schedulers';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\n\ntype BufferingEvent = (e: Event | React.SyntheticEvent) => void;\n\nconst MIN_READY_STATE = 3;\n// Avoid flickering when re-mounting previously buffered video\nconst DEBOUNCE = 200;\n\nexport default (noInitiallyBuffered = false) => {\n const [isBuffered, setIsBuffered] = useState(!noInitiallyBuffered);\n const [bufferedProgress, setBufferedProgress] = useState(0);\n\n const setIsBufferedDebounced = useMemo(() => {\n return debounce(setIsBuffered, DEBOUNCE, false, true);\n }, []);\n\n const handleBuffering = useCallback((e) => {\n const media = e.currentTarget as HTMLMediaElement;\n\n if (!isSafariPatchInProgress(media)) {\n if (media.buffered.length) {\n setBufferedProgress(media.buffered.end(0) / media.duration);\n }\n\n setIsBufferedDebounced(media.readyState >= MIN_READY_STATE || media.currentTime > 0);\n }\n }, [setIsBufferedDebounced]);\n\n const bufferingHandlers = {\n onLoadedData: handleBuffering,\n onPlaying: handleBuffering,\n onLoadStart: handleBuffering, // Needed for Safari to start\n onPause: handleBuffering, // Needed for Chrome when seeking\n onTimeUpdate: handleBuffering, // Needed for audio buffering progress\n onProgress: handleBuffering, // Needed for video buffering progress\n };\n\n return {\n isBuffered,\n bufferedProgress,\n bufferingHandlers,\n checkBuffering(element: HTMLMediaElement) {\n setIsBufferedDebounced(element.readyState >= MIN_READY_STATE);\n },\n };\n};\n","export default function focusEditableElement(element: HTMLElement, force?: boolean) {\n if (!force && element === document.activeElement) {\n return;\n }\n const selection = window.getSelection()!;\n const range = document.createRange();\n\n if (!element.lastChild || !element.lastChild.nodeValue) {\n element.focus();\n return;\n }\n\n range.setStart(element.lastChild, element.lastChild.nodeValue.length);\n selection.removeAllRanges();\n selection.addRange(range);\n}\n","import { ApiMessageEntity, ApiMessageEntityTypes, ApiFormattedText } from '../../../../api/types';\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nconst ENTITY_CLASS_BY_NODE_NAME: Record = {\n B: ApiMessageEntityTypes.Bold,\n STRONG: ApiMessageEntityTypes.Bold,\n I: ApiMessageEntityTypes.Italic,\n EM: ApiMessageEntityTypes.Italic,\n U: ApiMessageEntityTypes.Underline,\n S: ApiMessageEntityTypes.Strike,\n STRIKE: ApiMessageEntityTypes.Strike,\n DEL: ApiMessageEntityTypes.Strike,\n CODE: ApiMessageEntityTypes.Code,\n PRE: ApiMessageEntityTypes.Pre,\n BLOCKQUOTE: ApiMessageEntityTypes.Blockquote,\n};\n\nconst MAX_TAG_DEEPNESS = 3;\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default function parseMessageInput(html: string): ApiFormattedText {\n const fragment = document.createElement('div');\n fragment.innerHTML = parseMarkdown(html);\n const text = fragment.innerText.trim().replace(/\\u200b+/g, '').slice(0, MAX_MESSAGE_LENGTH);\n let textIndex = 0;\n let recursionDeepness = 0;\n const entities: ApiMessageEntity[] = [];\n\n function addEntity(node: ChildNode) {\n const { index, entity } = getEntityDataFromNode(node, text, textIndex);\n\n if (entity) {\n textIndex = index;\n entities.push(entity);\n } else if (node.textContent) {\n textIndex += node.textContent.length;\n }\n\n if (node.hasChildNodes() && recursionDeepness <= MAX_TAG_DEEPNESS) {\n recursionDeepness += 1;\n Array.from(node.childNodes).forEach(addEntity);\n }\n }\n\n Array.from(fragment.childNodes).forEach((node) => {\n recursionDeepness = 1;\n addEntity(node);\n });\n\n return {\n text,\n entities: entities.length ? entities : undefined,\n };\n}\n\nfunction parseMarkdown(html: string) {\n let parsedHtml = html.slice(0);\n\n if (!IS_EMOJI_SUPPORTED) {\n // Emojis\n parsedHtml = parsedHtml.replace(/]+alt=\"([^\"]+)\"[^>]*>/gm, '$1');\n }\n // Strip redundant tags\n parsedHtml = parsedHtml.replace(/<\\/?span([^>]*)?>/g, '');\n\n // Strip redundant nbsp's\n parsedHtml = parsedHtml.replace(/ /g, ' ');\n\n // Replace
with newline\n parsedHtml = parsedHtml.replace(/]*)?>/g, '\\n');\n\n // Strip redundant
tags\n parsedHtml = parsedHtml.replace(/<\\/div>(\\s*)
/g, '\\n');\n parsedHtml = parsedHtml.replace(/
/g, '\\n');\n parsedHtml = parsedHtml.replace(/<\\/div>/g, '');\n\n // Pre\n parsedHtml = parsedHtml.replace(/^`{3}(.*[\\n\\r][^]*?^)`{3}/gm, '
$1
');\n parsedHtml = parsedHtml.replace(/[`]{3}([^`]+)[`]{3}/g, '
$1
');\n\n // Code\n parsedHtml = parsedHtml.replace(/[`]{1}([^`\\n]+)[`]{1}/g, '$1');\n\n // Other simple markdown\n parsedHtml = parsedHtml.replace(/[*]{2}([^*\\n]+)[*]{2}/g, '$1');\n parsedHtml = parsedHtml.replace(/[*]{1}([^*\\n]+)[*]{1}/g, '$1');\n parsedHtml = parsedHtml.replace(/[~]{2}([^~\\n]+)[~]{2}/g, '$1');\n\n return parsedHtml;\n}\n\nfunction getEntityDataFromNode(\n node: ChildNode,\n rawText: string,\n textIndex: number,\n): { index: number; entity?: ApiMessageEntity } {\n const type = getEntityTypeFromNode(node);\n if (!type || !node.textContent) {\n return {\n index: textIndex,\n entity: undefined,\n };\n }\n\n const rawIndex = rawText.indexOf(node.textContent, textIndex);\n // In some cases, last text entity ends with a newline (which gets trimmed from `rawText`).\n // In this case, `rawIndex` would return `-1`, so we use `textIndex` instead.\n const index = rawIndex >= 0 ? rawIndex : textIndex;\n const offset = rawText.substring(0, index).length;\n const { length } = rawText.substring(index, index + node.textContent.length);\n\n let url: string | undefined;\n let userId: number | undefined;\n if (type === ApiMessageEntityTypes.TextUrl) {\n url = (node as HTMLAnchorElement).href;\n }\n if (type === ApiMessageEntityTypes.MentionName) {\n userId = Number((node as HTMLAnchorElement).dataset.userId);\n }\n\n return {\n index,\n entity: {\n type,\n offset,\n length,\n ...(url && { url }),\n ...(userId && { userId }),\n },\n };\n}\n\nfunction getEntityTypeFromNode(node: ChildNode) {\n if (ENTITY_CLASS_BY_NODE_NAME[node.nodeName]) {\n return ENTITY_CLASS_BY_NODE_NAME[node.nodeName];\n }\n\n if (node.nodeName === 'A') {\n const anchor = node as HTMLAnchorElement;\n if (anchor.dataset.entityType === ApiMessageEntityTypes.MentionName) {\n return ApiMessageEntityTypes.MentionName;\n }\n if (anchor.href.startsWith('mailto:')) {\n return ApiMessageEntityTypes.Email;\n }\n if (anchor.href.startsWith('tel:')) {\n return ApiMessageEntityTypes.Phone;\n }\n if (anchor.href !== anchor.textContent) {\n return ApiMessageEntityTypes.TextUrl;\n }\n\n return ApiMessageEntityTypes.Url;\n }\n\n if (node.nodeName === 'SPAN') {\n return (node as HTMLElement).dataset.entityType;\n }\n\n return undefined;\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport './DropTarget.scss';\n\nexport type OwnProps = {\n isQuick?: boolean;\n onFileSelect: (e: React.DragEvent) => void;\n};\n\nconst DropTarget: FC = ({ isQuick, onFileSelect }) => {\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n\n const handleDragEnter = () => { markHovered(); };\n const handleDragLeave = (e: React.DragEvent) => {\n const { relatedTarget: toTarget } = e;\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const className = buildClassName(\n 'DropTarget',\n isHovered && 'hovered',\n );\n\n return (\n \n
\n
\n
Drop files here to send them
\n
{isQuick ? 'in a quick way' : 'without compression'}
\n
\n
\n );\n};\n\nexport default memo(DropTarget);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport DropTarget from './DropTarget';\n\nimport './DropArea.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n withQuick?: boolean;\n onHide: NoneToVoidFunction;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n};\n\nexport enum DropAreaState {\n None = 'none',\n Document = 'document',\n QuickFile = 'quick_file',\n}\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst DropArea: FC = ({\n isOpen, withQuick, onHide, onFileSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef(null);\n const prevWithQuick = usePrevious(withQuick);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onHide) : undefined), [isOpen, onHide]);\n\n const handleFilesDrop = useCallback((e: React.DragEvent) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), false);\n }\n }, [onFileSelect, onHide]);\n\n const handleQuickFilesDrop = useCallback((e: React.DragEvent) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), true);\n }\n }, [onFileSelect, onHide]);\n\n const handleDragLeave = useCallback((e: React.DragEvent) => {\n e.stopPropagation();\n\n const { target: fromTarget, relatedTarget: toTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.DropTarget, .DropArea') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(() => {\n onHide();\n }, DROP_LEAVE_TIMEOUT_MS);\n }\n }, [onHide]);\n\n const handleDragOver = () => {\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n };\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'DropArea',\n transitionClassNames,\n );\n\n return (\n
\n \n {(withQuick || prevWithQuick) && }\n
\n );\n};\n\nexport default memo(DropArea);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport { getChatTitle, getUserFirstOrLastName, isChatPrivate } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\n\nimport './PickerSelectedItem.scss';\n\ntype OwnProps = {\n chatOrUserId?: number;\n icon?: string;\n title?: string;\n isMinimized?: boolean;\n canClose?: boolean;\n onClick: (arg: any) => void;\n clickArg: any;\n className?: string;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n user?: ApiUser;\n};\n\nconst PickerSelectedItem: FC = ({\n icon,\n title,\n isMinimized,\n canClose,\n onClick,\n clickArg,\n chat,\n user,\n className,\n}) => {\n useLang();\n\n let iconElement: any;\n let titleText: any;\n\n if (icon && title) {\n iconElement = (\n
\n \n
\n );\n\n titleText = title;\n } else if (chat || user) {\n iconElement = (\n \n );\n\n const name = !chat || (user && !user.isSelf)\n ? getUserFirstOrLastName(user)\n : getChatTitle(chat, user);\n\n titleText = name ? renderText(name) : undefined;\n }\n\n const fullClassName = buildClassName(\n 'PickerSelectedItem',\n className,\n isMinimized && 'minimized',\n canClose && 'closeable',\n );\n\n return (\n onClick(clickArg)}\n title={isMinimized ? titleText : undefined}\n >\n {iconElement}\n {!isMinimized && (\n
\n {titleText}\n
\n )}\n {canClose && (\n
\n \n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n if (!chatOrUserId) {\n return {};\n }\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n return {\n chat,\n user,\n };\n },\n)(PickerSelectedItem));\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nexport default (containerRef: RefObject, isDisabled?: boolean) => {\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n function handleScroll(e: WheelEvent) {\n // Ignore horizontal scroll and let it work natively (e.g. on touchpad)\n if (!e.deltaX) {\n container!.scrollLeft += e.deltaY / 4;\n }\n }\n\n container.addEventListener('wheel', handleScroll, { passive: true });\n\n return () => {\n container.removeEventListener('wheel', handleScroll);\n };\n }, [containerRef, isDisabled]);\n};\n","import { useEffect, useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\n\nimport { ApiMessage } from '../api/types';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (\n chatId: number,\n messageId?: number,\n message?: ApiMessage,\n replyOriginForId?: number,\n) => {\n const { loadMessage } = getDispatch();\n const loadMessageThrottled = useMemo(() => {\n const throttled = throttle(loadMessage, 500, true);\n return () => {\n throttled({ chatId, messageId, replyOriginForId });\n };\n }, [loadMessage, chatId, messageId, replyOriginForId]);\n\n useEffect(() => {\n if (messageId && !message) {\n loadMessageThrottled();\n }\n });\n};\n","import { RefObject } from 'react';\nimport { useState, useEffect, useCallback } from '../lib/teact/teact';\n\nimport { IAnchorPosition } from '../types';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../util/environment';\n\nconst LONG_TAP_DURATION_MS = 250;\nconst SELECTION_ANIMATION_DURATION_MS = 200;\n\nlet contextMenuCounter = 0;\n\nfunction checkIsDisabledForMobile() {\n return IS_MOBILE_SCREEN\n && window.document.body.classList.contains('enable-symbol-menu-transforms');\n}\n\nexport default (\n elementRef: RefObject,\n isMenuDisabled?: boolean,\n) => {\n const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);\n const [contextMenuPosition, setContextMenuPosition] = useState(undefined);\n\n const handleBeforeContextMenu = useCallback((e: React.MouseEvent) => {\n if (!isMenuDisabled && e.button === 2) {\n document.body.classList.add('no-selection');\n }\n }, [isMenuDisabled]);\n\n const handleContextMenu = useCallback((e: React.MouseEvent) => {\n if (isMenuDisabled) {\n return;\n }\n e.preventDefault();\n document.body.classList.remove('no-selection');\n\n if (contextMenuPosition) {\n return;\n }\n document.body.classList.remove('no-selection');\n if (contextMenuCounter === 0) {\n document.body.classList.add('has-context-menu');\n }\n contextMenuCounter++;\n\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: e.clientX, y: e.clientY });\n }, [isMenuDisabled, contextMenuPosition]);\n\n const handleContextMenuClose = useCallback(() => {\n setIsContextMenuOpen(false);\n }, []);\n\n const handleContextMenuHide = useCallback(() => {\n setContextMenuPosition(undefined);\n document.body.classList.remove('no-selection');\n\n setTimeout(() => {\n contextMenuCounter--;\n if (contextMenuCounter === 0) {\n document.body.classList.remove('has-context-menu');\n }\n }, SELECTION_ANIMATION_DURATION_MS);\n }, []);\n\n // Support context menu on touch-devices\n useEffect(() => {\n if (isMenuDisabled || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (!element) {\n return undefined;\n }\n\n let timer: number | undefined;\n\n const clearLongPressTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const emulateContextMenuEvent = (originalEvent: TouchEvent) => {\n clearLongPressTimer();\n\n const { clientX, clientY } = originalEvent.touches[0];\n\n if (contextMenuPosition) {\n return;\n }\n\n // temporarily intercept and clear the next click\n element.addEventListener('touchend', function cancelClickOnce(e) {\n element.removeEventListener('touchend', cancelClickOnce, true);\n e.stopImmediatePropagation();\n e.preventDefault();\n e.stopPropagation();\n }, true);\n\n document.body.classList.add('no-selection');\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: clientX, y: clientY });\n };\n\n const startLongPressTimer = (e: TouchEvent) => {\n if (isMenuDisabled || checkIsDisabledForMobile()) {\n return;\n }\n clearLongPressTimer();\n\n timer = window.setTimeout(() => emulateContextMenuEvent(e), LONG_TAP_DURATION_MS);\n };\n\n // @perf Consider event delegation\n element.addEventListener('touchstart', startLongPressTimer, { passive: true });\n element.addEventListener('touchcancel', clearLongPressTimer, true);\n element.addEventListener('touchend', clearLongPressTimer, true);\n element.addEventListener('touchmove', clearLongPressTimer, { passive: true });\n\n return () => {\n clearLongPressTimer();\n element.removeEventListener('touchstart', startLongPressTimer);\n element.removeEventListener('touchcancel', clearLongPressTimer, true);\n element.removeEventListener('touchend', clearLongPressTimer, true);\n element.removeEventListener('touchmove', clearLongPressTimer);\n };\n }, [contextMenuPosition, isMenuDisabled, elementRef]);\n\n return {\n isContextMenuOpen,\n contextMenuPosition,\n handleBeforeContextMenu,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n };\n};\n","export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMessageEntity, ApiMessageEntityTypes, ApiMessage } from '../../../api/types';\n\nimport { getMessageText } from '../../../modules/helpers';\nimport renderText from './renderText';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\nexport type TextPart = string | Element;\n\nexport function renderMessageText(message: ApiMessage, highlight?: string, shouldRenderHqEmoji?: boolean) {\n const formattedText = message.content.text;\n\n if (!formattedText || !formattedText.text) {\n const rawText = getMessageText(message);\n return rawText ? [rawText] : undefined;\n }\n const { text, entities } = formattedText;\n\n return renderTextWithEntities(text, entities, highlight, shouldRenderHqEmoji);\n}\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set;\n nestedEntities: IOrganizedEntity[];\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter(Boolean as any);\n\n nestedEntities.forEach((e) => e.organizedIndexes.forEach((i) => organizedIndexes.add(i)));\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntites = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntites.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntites.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n if (!entityText) {\n return renderMessagePart(renderedContent);\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.Blockquote:\n return
{renderMessagePart(renderedContent)}
;\n case ApiMessageEntityTypes.BotCommand:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Code:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.Email:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Italic:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.MentionName:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Mention:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Phone:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Pre:\n return
{renderMessagePart(renderedContent)}
;\n case ApiMessageEntityTypes.Strike:\n return {renderMessagePart(renderedContent)};\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n \n {renderMessagePart(renderedContent)}\n \n );\n case ApiMessageEntityTypes.Underline:\n return {renderMessagePart(renderedContent)};\n default:\n return renderMessagePart(renderedContent);\n }\n}\n\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n if (highlight) {\n return renderText(content, [emojiFilter, 'br', 'highlight'], { highlight });\n } else {\n return renderText(content, [emojiFilter, 'br']);\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent) {\n getDispatch().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent) {\n getDispatch().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getDispatch().searchTextMessagesLocal();\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Italic:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Underline:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Code:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`
${renderedContent}
\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.MentionName:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `${renderedContent}`;\n default:\n return renderedContent;\n }\n}\n","import { useEffect, useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport { imgToCanvas } from '../util/files';\nimport useForceUpdate from './useForceUpdate';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\nconst MAX_CACHE_SIZE = 1000;\n\nconst cache = new Map();\n\nexport default function useBlur(dataUri?: string, isDisabled = false, delay?: number) {\n const blurredRef = useRef(dataUri ? cache.get(dataUri) : undefined);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n\n if (timeoutRef.current && isDisabled) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useEffect(() => {\n if (!dataUri || blurredRef.current || isDisabled) {\n return;\n }\n\n const img = new Image();\n\n img.onload = () => {\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n const blurredDataUri = canvas.toDataURL();\n\n blurredRef.current = blurredDataUri;\n forceUpdate();\n\n if (cache.size >= MAX_CACHE_SIZE) {\n cache.clear();\n }\n cache.set(dataUri, blurredDataUri);\n };\n\n if (delay) {\n timeoutRef.current = window.setTimeout(() => {\n img.src = dataUri;\n }, delay);\n } else {\n img.src = dataUri;\n }\n }, [dataUri, delay, forceUpdate, isDisabled]);\n\n return blurredRef.current;\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\nimport { fastRaf } from '../util/schedulers';\n\n// Fix for memory leak when unmounting video element\nexport default function useVideoCleanup(videoRef: RefObject, dependencies: any[]) {\n useEffect(() => {\n const videoEl = videoRef.current;\n\n return () => {\n if (videoEl) {\n fastRaf(() => {\n videoEl.pause();\n videoEl.src = '';\n videoEl.load();\n });\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n}\n","import { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl: string) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await navigator.clipboard.write([\n new window.ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useRef, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from './Loading';\nimport Button from './Button';\n\nimport './SearchInput.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n children?: any;\n className?: string;\n inputId?: string;\n value?: string;\n focused?: boolean;\n isLoading?: boolean;\n placeholder?: string;\n disabled?: boolean;\n canClose?: boolean;\n onChange: (value: string) => void;\n onReset?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n onBlur?: NoneToVoidFunction;\n};\n\nconst SearchInput: FC = ({\n ref,\n children,\n value,\n inputId,\n className,\n focused,\n isLoading,\n placeholder,\n disabled,\n canClose,\n onChange,\n onReset,\n onFocus,\n onBlur,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let inputRef = useRef(null);\n if (ref) {\n inputRef = ref;\n }\n\n const [isInputFocused, markInputFocused, unmarkInputFocused] = useFlag(focused);\n\n useEffect(() => {\n if (!inputRef.current) {\n return;\n }\n\n if (focused) {\n inputRef.current.focus();\n } else {\n inputRef.current.blur();\n }\n }, [focused, placeholder]); // Trick for setting focus when selecting a contact to search for\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent) {\n const { currentTarget } = event;\n onChange(currentTarget.value);\n }\n\n function handleFocus() {\n markInputFocused();\n if (onFocus) {\n onFocus();\n }\n }\n\n function handleBlur() {\n unmarkInputFocused();\n if (onBlur) {\n onBlur();\n }\n }\n\n return (\n
\n {children}\n \n \n {isLoading && (\n \n )}\n {!isLoading && (value || canClose) && onReset && (\n \n \n \n )}\n
\n );\n};\n\nexport default memo(SearchInput);\n","import { fastRaf } from './schedulers';\nimport { animate } from './animation';\nimport { IS_IOS } from './environment';\n\nconst DURATION = 450;\n\nexport default function fastSmoothScroll(container: HTMLElement, left: number) {\n // Native way seems to be smoother in Chrome\n if (!IS_IOS) {\n container.scrollTo({ left, behavior: 'smooth' });\n } else {\n fastRaf(() => {\n scrollWithJs(container, left);\n });\n }\n}\n\nfunction scrollWithJs(container: HTMLElement, left: number) {\n const { scrollLeft, offsetWidth: containerWidth, scrollWidth } = container;\n let path = left - scrollLeft;\n\n if (path < 0) {\n const remainingPath = -scrollLeft;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollWidth - (scrollLeft + containerWidth);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollLeft + path;\n const startAt = Date.now();\n\n animate(() => {\n const t = Math.min((Date.now() - startAt) / DURATION, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollLeft = Math.round(target - currentPath);\n\n return t < 1;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { IS_IOS } from './environment';\n\nexport default (container: HTMLDivElement, scrollTop?: number) => {\n if (IS_IOS) {\n container.style.overflow = 'hidden';\n }\n\n if (scrollTop !== undefined) {\n container.scrollTop = scrollTop;\n }\n\n if (IS_IOS) {\n container.style.overflow = '';\n }\n};\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\n\nimport { selectUser } from '../../modules/selectors';\nimport { getUserFirstOrLastName } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\n\nimport './TypingStatus.scss';\n\ntype OwnProps = {\n typingStatus: ApiTypingStatus;\n};\n\ntype StateProps = {\n typingUser?: ApiUser;\n};\n\nconst TypingStatus: FC = ({ typingStatus, typingUser }) => {\n const typingUserName = typingUser && !typingUser.isSelf && getUserFirstOrLastName(typingUser);\n\n return (\n

\n {typingUserName && (\n {renderText(typingUserName)}\n )}\n {typingStatus.action}\n \n

\n );\n};\n\nexport default memo(withGlobal(\n (global, { typingStatus }): StateProps => {\n if (!typingStatus.userId) {\n return {};\n }\n\n const typingUser = selectUser(global, typingStatus.userId);\n\n return { typingUser };\n },\n)(TypingStatus));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n getChatTitle,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './DeleteChatModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n chat: ApiChat;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isChatWithSelf?: boolean;\n isPrivateChat: boolean;\n isBasicGroup: boolean;\n isSuperGroup: boolean;\n canDeleteForAll?: boolean;\n chatTitle: string;\n contactName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteChatModal: FC = ({\n isOpen,\n chat,\n isChannel,\n isPrivateChat,\n isChatWithSelf,\n isBasicGroup,\n isSuperGroup,\n canDeleteForAll,\n chatTitle,\n contactName,\n onClose,\n leaveChannel,\n deleteHistory,\n deleteChannel,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: true });\n onClose();\n }, [deleteHistory, chat.id, chat.lastMessage, onClose]);\n\n const handleDeleteChat = useCallback(() => {\n if (isPrivateChat || isBasicGroup) {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: false });\n } else if ((isChannel || isSuperGroup) && !chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else if ((isChannel || isSuperGroup) && chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n }\n onClose();\n }, [\n isPrivateChat,\n isBasicGroup,\n isChannel,\n isSuperGroup,\n chat.isCreator,\n chat.lastMessage,\n chat.id,\n onClose,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n ]);\n\n const lang = useLang();\n\n function renderHeader() {\n return (\n
\n \n

{renderTitle()}

\n
\n );\n }\n\n function renderTitle() {\n if (isChannel && !chat.isCreator) {\n return 'Leave Channel?';\n }\n\n if (isChannel && chat.isCreator) {\n return 'Delete and Leave Channel?';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Leave Group?';\n }\n\n return 'Delete Chat?';\n }\n\n function renderMessage() {\n if (isChannel && !chat.isCreator) {\n return

Are you sure you want to leave channel {chatTitle}?

;\n }\n if (isChannel && chat.isCreator) {\n return

Are you sure you want to delete and leave channel {chatTitle}?

;\n }\n\n if (isBasicGroup || isSuperGroup) {\n return

Are you sure you want to leave group {chatTitle}?

;\n }\n\n return

Are you sure you want to delete chat with {contactName}?

;\n }\n\n function renderActionText() {\n if (isChannel && !chat.isCreator) {\n return 'Leave Channel';\n }\n if (isChannel && chat.isCreator) {\n return 'Delete and Leave Channel';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Leave Group';\n }\n\n return `Delete${canDeleteForAll ? ' just for me' : ''}`;\n }\n\n return (\n \n {renderMessage()}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chat }): StateProps => {\n const isPrivateChat = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, chat.id);\n const canDeleteForAll = (isPrivateChat && !isChatWithSelf);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel: isChatChannel(chat),\n isBasicGroup: isChatBasicGroup(chat),\n isSuperGroup: isChatSuperGroup(chat),\n canDeleteForAll,\n chatTitle: getChatTitle(chat),\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['leaveChannel', 'deleteHistory', 'deleteChannel']),\n)(DeleteChatModal));\n","/*\n * Thanks to Ace Monkey for this mind-blowing patch.\n */\n\nexport function patchSafariProgressiveAudio(audioEl: HTMLAudioElement) {\n if (audioEl.dataset.patchedForSafari) {\n return;\n }\n\n audioEl.addEventListener('play', () => {\n const t = audioEl.currentTime;\n\n function onProgress() {\n if (!audioEl.buffered.length) {\n return;\n }\n\n audioEl.dataset.patchForSafariInProgress = 'true';\n audioEl.currentTime = audioEl.duration - 1;\n audioEl.addEventListener('progress', () => {\n delete audioEl.dataset.patchForSafariInProgress;\n audioEl.currentTime = t;\n if (audioEl.paused) {\n audioEl.play();\n }\n }, { once: true });\n\n audioEl.removeEventListener('progress', onProgress);\n }\n\n audioEl.addEventListener('progress', onProgress);\n }, { once: true });\n\n audioEl.dataset.patchedForSafari = 'true';\n}\n\nexport function isSafariPatchInProgress(audioEl: HTMLAudioElement) {\n return Boolean(audioEl.dataset.patchForSafariInProgress);\n}\n","import { useLayoutEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useLayoutEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import React, {\n FC, useCallback, useEffect, useState, memo, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getDocumentExtension, getDocumentHasPreview } from './helpers/documentInfo';\nimport { getMediaTransferState, getMessageMediaHash, getMessageMediaThumbDataUri } from '../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../hooks/useMedia';\nimport download from '../../util/download';\n\nimport File from './File';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n smaller?: boolean;\n isSelected?: boolean;\n isSelectable?: boolean;\n uploadProgress?: number;\n withDate?: boolean;\n datetime?: number;\n className?: string;\n sender?: string;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Document: FC = ({\n message,\n observeIntersection,\n smaller,\n uploadProgress,\n withDate,\n datetime,\n className,\n sender,\n isSelected,\n isSelectable,\n onCancelUpload,\n onDateClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const document = message.content.document!;\n const extension = getDocumentExtension(document) || '';\n const { fileName, size, timestamp } = document;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, 'download'), !isDownloadAllowed);\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isDownloadAllowed);\n\n const hasPreview = getDocumentHasPreview(document);\n const thumbDataUri = hasPreview ? getMessageMediaThumbDataUri(message) : undefined;\n const localBlobUrl = hasPreview ? document.previewBlobUrl : undefined;\n const previewData = useMedia(getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [isUploading, onCancelUpload]);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n useEffect(() => {\n if (isDownloadAllowed && mediaData) {\n download(mediaData, fileName);\n setIsDownloadAllowed(false);\n }\n }, [fileName, mediaData, isDownloadAllowed]);\n\n return (\n \n );\n};\n\nexport default memo(Document);\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './StickerSetModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst StickerSetModalAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerSetModal = useModuleLoader(Bundles.Extra, 'StickerSetModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSetModal ? : undefined;\n};\n\nexport default StickerSetModalAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IAnchorPosition } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useVirtualBackdrop from '../../../hooks/useVirtualBackdrop';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './TextFormatter.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n anchorPosition?: IAnchorPosition;\n selectedRange?: Range;\n onClose: () => void;\n};\n\ninterface ISelectedTextFormats {\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strikethrough?: boolean;\n monospace?: boolean;\n}\n\nconst TEXT_FORMAT_BY_TAG_NAME: Record = {\n B: 'bold',\n STRONG: 'bold',\n I: 'italic',\n EM: 'italic',\n U: 'underline',\n DEL: 'strikethrough',\n CODE: 'monospace',\n};\n\nconst TextFormatter: FC = ({\n isOpen,\n anchorPosition,\n selectedRange,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const linkUrlInputRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n const [isLinkControlOpen, openLinkControl, closeLinkControl] = useFlag();\n const [linkUrl, setLinkUrl] = useState('');\n const [isEditingLink, setIsEditingLink] = useState(false);\n const [inputClassName, setInputClassName] = useState();\n const [selectedTextFormats, setSelectedTextFormats] = useState({});\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n useVirtualBackdrop(\n isOpen,\n containerRef,\n onClose,\n );\n\n useEffect(() => {\n if (isLinkControlOpen) {\n linkUrlInputRef.current!.focus();\n } else {\n setLinkUrl('');\n setIsEditingLink(false);\n }\n }, [isLinkControlOpen]);\n\n useEffect(() => {\n if (!shouldRender) {\n closeLinkControl();\n setSelectedTextFormats({});\n setInputClassName(undefined);\n }\n }, [closeLinkControl, shouldRender]);\n\n useEffect(() => {\n if (!isOpen || !selectedRange) {\n return;\n }\n\n const selectedFormats: ISelectedTextFormats = {};\n let { parentElement } = selectedRange.commonAncestorContainer;\n while (parentElement && parentElement.id !== EDITABLE_INPUT_ID) {\n const textFormat = TEXT_FORMAT_BY_TAG_NAME[parentElement.tagName];\n if (textFormat) {\n selectedFormats[textFormat] = true;\n }\n\n parentElement = parentElement.parentElement;\n }\n\n setSelectedTextFormats(selectedFormats);\n }, [isOpen, selectedRange, openLinkControl]);\n\n function restoreSelection() {\n if (!selectedRange) {\n return;\n }\n\n const selection = window.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(selectedRange);\n }\n }\n\n const getSelectedText = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.toString();\n }, [selectedRange]);\n\n const getSelectedElement = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.commonAncestorContainer.parentElement;\n }, [selectedRange]);\n\n function updateInputStyles() {\n const input = linkUrlInputRef.current;\n if (!input) {\n return;\n }\n\n const { offsetWidth, scrollWidth, scrollLeft } = input;\n if (scrollWidth <= offsetWidth) {\n setInputClassName(undefined);\n return;\n }\n\n let className = '';\n if (scrollLeft < scrollWidth - offsetWidth) {\n className = 'mask-right';\n }\n if (scrollLeft > 0) {\n className += ' mask-left';\n }\n\n setInputClassName(className);\n }\n\n function handleLinkUrlChange(e: React.ChangeEvent) {\n setLinkUrl(e.target.value);\n updateInputStyles();\n }\n\n function getFormatButtonClassName(key: keyof ISelectedTextFormats) {\n if (selectedTextFormats[key]) {\n return 'active';\n }\n\n if (key === 'monospace' || key === 'strikethrough') {\n if (Object.keys(selectedTextFormats).some(\n (fKey) => fKey !== key && !!selectedTextFormats[fKey as keyof ISelectedTextFormats],\n )) {\n return 'disabled';\n }\n } else if (selectedTextFormats.monospace || selectedTextFormats.strikethrough) {\n return 'disabled';\n }\n\n return undefined;\n }\n\n const handleBoldText = useCallback(() => {\n setSelectedTextFormats((selectedFormats) => {\n // Somehow re-applying 'bold' command to already bold text doesn't work\n document.execCommand(selectedFormats.bold ? 'removeFormat' : 'bold');\n Object.keys(selectedFormats).forEach((key) => {\n if ((key === 'italic' || key === 'underline') && !!selectedFormats[key]) {\n document.execCommand(key);\n }\n });\n\n return {\n ...selectedFormats,\n bold: !selectedFormats.bold,\n };\n });\n }, []);\n\n const handleItalicText = useCallback(() => {\n document.execCommand('italic');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n italic: !selectedFormats.italic,\n }));\n }, []);\n\n const handleUnderlineText = useCallback(() => {\n document.execCommand('underline');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n underline: !selectedFormats.underline,\n }));\n }, []);\n\n const handleStrikethroughText = useCallback(() => {\n if (selectedTextFormats.strikethrough) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'DEL'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n strikethrough: false,\n }));\n\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.strikethrough,\n ]);\n\n const handleMonospaceText = useCallback(() => {\n if (selectedTextFormats.monospace) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'CODE'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n monospace: false,\n }));\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.monospace,\n ]);\n\n function handleLinkUrlConfirm() {\n const formattedLinkUrl = linkUrl.includes('://') ? linkUrl : `http://${linkUrl}`;\n\n if (isEditingLink) {\n const element = getSelectedElement();\n if (!element || element.tagName !== 'A') {\n return;\n }\n\n (element as HTMLAnchorElement).href = formattedLinkUrl;\n\n onClose();\n return;\n }\n\n const text = getSelectedText();\n restoreSelection();\n document.execCommand('insertHTML', false, `${text}`);\n onClose();\n }\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n const HANDLERS_BY_KEY_CODE: Record = {\n KeyK: openLinkControl,\n KeyB: handleBoldText,\n KeyU: handleUnderlineText,\n KeyI: handleItalicText,\n KeyM: handleMonospaceText,\n KeyS: handleStrikethroughText,\n };\n\n const handler = HANDLERS_BY_KEY_CODE[e.code];\n\n if (\n e.altKey\n || !(e.ctrlKey || e.metaKey)\n || !handler\n ) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n handler();\n }, [\n handleBoldText, handleItalicText, handleUnderlineText,\n handleMonospaceText, handleStrikethroughText,\n openLinkControl,\n ]);\n\n useEffect(() => {\n if (isOpen) {\n document.addEventListener('keydown', handleKeyDown);\n }\n\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [isOpen, handleKeyDown]);\n\n const lang = useLang();\n\n function handleContainerKeyDown(e: React.KeyboardEvent) {\n if (e.key === 'Enter' && isLinkControlOpen) {\n handleLinkUrlConfirm();\n e.preventDefault();\n }\n }\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'TextFormatter',\n transitionClassNames,\n isLinkControlOpen && 'link-control-shown',\n );\n\n const linkUrlConfirmClassName = buildClassName(\n 'TextFormatter-link-url-confirm',\n !!linkUrl.length && 'shown',\n );\n\n const style = anchorPosition\n ? `left: ${anchorPosition.x}px; top: ${anchorPosition.y}px;--text-formatter-left: ${anchorPosition.x}px;`\n : '';\n\n return (\n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n\n
\n
\n \n
\n\n \n \n
\n\n
\n
\n \n \n \n
\n
\n
\n
\n );\n};\n\nexport default memo(TextFormatter);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport {\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n} from '../../modules/helpers';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\n\nimport './Media.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n idPrefix?: string;\n onClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Media: FC = ({ message, idPrefix = 'shared-media', onClick }) => {\n const handleClick = useCallback(() => {\n onClick!(message.id, message.chatId);\n }, [message.id, message.chatId, onClick]);\n\n const thumbDataUri = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(mediaBlobUrl, 'slow');\n\n const video = getMessageVideo(message);\n\n return (\n
\n {shouldRenderThumb && (\n \"\"\n )}\n {shouldRenderFullMedia && (\n \"\"\n )}\n {video && {video.isGif ? 'GIF' : formatMediaDuration(video.duration)}}\n
\n );\n};\n\nexport default memo(Media);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiAudio, ApiMessage, ApiVoice,\n} from '../../api/types';\nimport { ISettings } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDateTime, formatMediaDuration, formatPastTimeShort } from '../../util/dateFormat';\nimport {\n getMediaDuration,\n getMediaTransferState,\n getMessageKey,\n getMessageMediaFormat,\n getMessageMediaHash,\n isMessageLocal,\n isOwnMessage,\n} from '../../modules/helpers';\nimport { renderWaveformToDataUri } from './helpers/waveform';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport { decodeWaveform, interpolateArray } from '../../util/waveform';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './Audio.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n uploadProgress?: number;\n renderingFor?: 'searchResult' | 'sharedMedia';\n date?: number;\n lastSyncTime?: number;\n className?: string;\n isSelectable?: boolean;\n isSelected?: boolean;\n onPlay: (messageId: number, chatId: number) => void;\n onReadMedia?: () => void;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n};\n\ninterface ISeekMethods {\n handleStartSeek: (e: React.MouseEvent) => void;\n handleSeek: (e: React.MouseEvent) => void;\n handleStopSeek: () => void;\n}\n\nconst AVG_VOICE_DURATION = 30;\nconst MIN_SPIKES = IS_MOBILE_SCREEN ? 20 : 25;\nconst MAX_SPIKES = IS_MOBILE_SCREEN ? 50 : 75;\n// This is needed for browsers requiring user interaction before playing.\nconst PRELOAD = true;\n\nconst Audio: FC = ({\n theme,\n message,\n senderTitle,\n uploadProgress,\n renderingFor,\n date,\n lastSyncTime,\n className,\n isSelectable,\n isSelected,\n onPlay,\n onReadMedia,\n onCancelUpload,\n onDateClick,\n}) => {\n const { content: { audio, voice }, isMediaUnread } = message;\n const isVoice = Boolean(voice);\n const isSeeking = useRef(false);\n\n const [isActivated, setIsActivated] = useState(false);\n const shouldDownload = (isActivated || PRELOAD) && lastSyncTime;\n\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n );\n\n function handleForcePlay() {\n setIsActivated(true);\n onPlay(message.id, message.chatId);\n }\n\n const {\n isBuffered, bufferedProgress, bufferingHandlers, checkBuffering,\n } = useBuffering();\n\n const {\n isPlaying, playProgress, playPause, setCurrentTime, duration,\n } = useAudioPlayer(\n getMessageKey(message),\n getMediaDuration(message)!,\n mediaData,\n bufferingHandlers,\n checkBuffering,\n isActivated,\n handleForcePlay,\n isMessageLocal(message),\n );\n\n useEffect(() => {\n setIsActivated(isPlaying);\n }, [isPlaying]);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isActivated && !isBuffered);\n\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring);\n\n const handleButtonClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n\n return;\n }\n\n if (!isPlaying) {\n onPlay(message.id, message.chatId);\n }\n\n setIsActivated(!isActivated);\n playPause();\n }, [isPlaying, isUploading, message.id, message.chatId, onCancelUpload, onPlay, playPause, isActivated]);\n\n useEffect(() => {\n if (isPlaying && onReadMedia && isMediaUnread) {\n onReadMedia();\n }\n }, [isPlaying, isMediaUnread, onReadMedia]);\n\n const handleSeek = useCallback((e: React.MouseEvent) => {\n if (isSeeking.current) {\n const seekBar = e.currentTarget.closest('.seekline,.waveform');\n if (seekBar) {\n const { width, left } = seekBar.getBoundingClientRect();\n setCurrentTime(duration * ((e.clientX - left) / width));\n }\n }\n }, [duration, setCurrentTime]);\n\n const handleStartSeek = useCallback((e: React.MouseEvent) => {\n isSeeking.current = true;\n handleSeek(e);\n }, [handleSeek]);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n }, []);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n useLang();\n\n function getFirstLine() {\n if (isVoice) {\n return senderTitle || 'Voice';\n }\n\n const { title, fileName } = audio!;\n\n return title || fileName;\n }\n\n function getSecondLine() {\n if (isVoice) {\n return formatMediaDuration(voice!.duration);\n }\n\n const { performer } = audio!;\n\n return (\n <>\n {performer && renderText(performer)}\n {performer && senderTitle && }\n {senderTitle && renderText(senderTitle)}\n \n );\n }\n\n const seekHandlers = { handleStartSeek, handleSeek, handleStopSeek };\n const isOwn = isOwnMessage(message);\n const renderedWaveform = useMemo(\n () => voice && renderWaveform(voice, playProgress, isOwn, seekHandlers, theme),\n [voice, playProgress, isOwn, seekHandlers, theme],\n );\n\n const fullClassName = buildClassName(\n 'Audio media-inner',\n className,\n isOwn && !renderingFor && 'own',\n renderingFor && 'bigger',\n isSelected && 'audio-is-selected',\n );\n\n const buttonClassNames = ['toggle-play'];\n if (shouldRenderSpinner) {\n buttonClassNames.push('loading');\n } else if (isPlaying) {\n buttonClassNames.push('pause');\n } else if (!isPlaying) {\n buttonClassNames.push('play');\n }\n\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n const contentClassName = buildClassName('content', showSeekline && 'with-seekline');\n\n function renderSearchResult() {\n return (\n <>\n
\n
\n

{renderText(getFirstLine())}

\n\n
\n {date && (\n \n {formatPastTimeShort(date * 1000)}\n \n )}\n
\n
\n\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n

\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {getSecondLine()}\n

\n )}\n
\n \n );\n }\n\n return (\n
\n {isSelectable && (\n
\n {isSelected && }\n
\n )}\n \n \n \n \n {shouldRenderSpinner && (\n
\n \n
\n )}\n {renderingFor === 'searchResult' && renderSearchResult()}\n {renderingFor !== 'searchResult' && audio && renderAudio(\n audio, isPlaying, playProgress, bufferedProgress, seekHandlers, date,\n onDateClick ? handleDateClick : undefined,\n )}\n {renderingFor !== 'searchResult' && voice && renderVoice(voice, renderedWaveform, isMediaUnread)}\n
\n );\n};\n\nfunction renderAudio(\n audio: ApiAudio,\n isPlaying: boolean,\n playProgress: number,\n bufferedProgress: number,\n seekHandlers: ISeekMethods,\n date?: number,\n handleDateClick?: () => void,\n) {\n const {\n title, performer, duration, fileName,\n } = audio;\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n\n return (\n
\n

{renderText(title || fileName)}

\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n
\n {renderText(performer || 'Unknown')}\n {date && (\n <>\n {' '}\n •\n {' '}\n {formatMediaDateTime(date * 1000)}\n \n )}\n
\n )}\n

\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {formatMediaDuration(duration)}\n

\n
\n );\n}\n\nfunction renderVoice(voice: ApiVoice, renderedWaveform: any, isMediaUnread?: boolean) {\n return (\n
\n {renderedWaveform}\n

\n {formatMediaDuration(voice.duration)}\n {isMediaUnread && }\n

\n
\n );\n}\n\nfunction renderWaveform(\n voice: ApiVoice,\n playProgress = 0,\n isOwn = false,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n theme: ISettings['theme'],\n) {\n const { waveform, duration } = voice;\n\n if (!waveform) {\n return undefined;\n }\n\n const fillColor = theme === 'dark' ? '#494B75' : '#CBCBCB';\n const fillOwnColor = theme === 'dark' ? '#C69C85' : '#B0DEA6';\n const progressFillColor = theme === 'dark' ? '#868DF5' : '#54a3e6';\n const progressFillOwnColor = theme === 'dark' ? '#FFFFFF' : '#53ad53';\n const durationFactor = Math.min(duration / AVG_VOICE_DURATION, 1);\n const spikesCount = Math.round(MIN_SPIKES + (MAX_SPIKES - MIN_SPIKES) * durationFactor);\n const decodedWaveform = decodeWaveform(new Uint8Array(waveform));\n const { data: spikes, peak } = interpolateArray(decodedWaveform, spikesCount);\n const { src, width, height } = renderWaveformToDataUri(spikes, playProgress, {\n peak,\n fillStyle: isOwn ? fillOwnColor : fillColor,\n progressFillStyle: isOwn ? progressFillOwnColor : progressFillColor,\n });\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n \n );\n}\n\nfunction renderSeekline(\n playProgress: number,\n bufferedProgress: number,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n) {\n return (\n \n \n \n \n \n \n \n \n \n \n
\n );\n}\n\nexport default memo(withGlobal((global) => ({ theme: global.settings.byKey.theme }))(Audio));\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","type IWaveformProps = {\n peak: number;\n fillStyle: string;\n progressFillStyle: string;\n};\n\nconst SPIKE_WIDTH = 2;\nconst SPIKE_STEP = 4;\nconst SPIKE_RADIUS = 1;\nconst HEIGHT = 23;\n\nexport function renderWaveformToDataUri(\n spikes: number[],\n progress: number,\n {\n peak, fillStyle, progressFillStyle,\n }: IWaveformProps,\n) {\n const width = spikes.length * SPIKE_STEP;\n const height = HEIGHT;\n\n const canvas = document.createElement('canvas');\n canvas.width = width * 2;\n canvas.height = height * 2;\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d')!;\n ctx.scale(2, 2);\n\n spikes.forEach((item, i) => {\n ctx.globalAlpha = (i / spikes.length >= progress) ? 0.5 : 1;\n ctx.fillStyle = progress > i / spikes.length ? progressFillStyle : fillStyle;\n const spikeHeight = Math.max(2, HEIGHT * (item / Math.max(1, peak)));\n roundedRectangle(ctx, i * SPIKE_STEP, height, SPIKE_WIDTH, spikeHeight, SPIKE_RADIUS);\n ctx.fill();\n });\n\n return {\n src: canvas.toDataURL(),\n width,\n height,\n };\n}\n\nfunction roundedRectangle(\n ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number,\n) {\n if (width < 2 * radius) {\n radius = width / 2;\n }\n if (height < 2 * radius) {\n radius = height / 2;\n }\n\n ctx.beginPath();\n ctx.moveTo(x + radius, y);\n ctx.arcTo(x + width, y, x + width, y - height, radius);\n ctx.arcTo(x + width, y - height, x, y - height, radius);\n ctx.arcTo(x, y - height, x, y, radius);\n ctx.arcTo(x, y, x + width, y, radius);\n ctx.closePath();\n}\n","import React, {\n FC, useLayoutEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Tab.scss';\n\ntype OwnProps = {\n className?: string;\n title: string;\n active?: boolean;\n badgeCount?: number;\n isBadgeActive?: boolean;\n previousActiveTab?: number;\n onClick: (arg: number) => void;\n clickArg: number;\n};\n\nconst Tab: FC = ({\n className,\n title,\n active,\n badgeCount,\n isBadgeActive,\n previousActiveTab,\n onClick,\n clickArg,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const tabRef = useRef(null);\n\n useLayoutEffect(() => {\n if (!active || previousActiveTab === undefined) {\n return;\n }\n\n const tab = tabRef.current!;\n const indicator = tab.querySelector('i')!;\n const currentIndicator = tab.parentElement!.children[previousActiveTab].querySelector('i')!;\n\n currentIndicator.classList.remove('animate');\n indicator.classList.remove('animate');\n\n // We move and resize our indicator so it repeats the position and size of the previous one.\n const shiftLeft = currentIndicator.parentElement!.offsetLeft - indicator.parentElement!.offsetLeft;\n const scaleFactor = currentIndicator.clientWidth / indicator.clientWidth;\n indicator.style.transform = `translate3d(${shiftLeft}px, 0, 0) scale3d(${scaleFactor}, 1, 1)`;\n\n // 3 AFs needed here to synchronize animations with Transition component\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Now we remove the transform to let it animate to its own position and size.\n indicator.classList.add('animate');\n indicator.style.transform = 'none';\n });\n });\n });\n }, [active, previousActiveTab]);\n\n return (\n onClick(clickArg)}\n ref={tabRef}\n >\n \n {title}\n {!!badgeCount && (\n {badgeCount}\n )}\n \n \n \n );\n};\n\nexport default memo(Tab);\n","import React, {\n FC, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport fastSmoothScrollHorizontal from '../../util/fastSmoothScrollHorizontal';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHorizontalScroll from '../../hooks/useHorizontalScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Tab from './Tab';\n\nimport './TabList.scss';\n\nexport type TabWithProperties = {\n title: string;\n badgeCount?: number;\n isBadgeActive?: boolean;\n};\n\ntype OwnProps = {\n tabs: readonly TabWithProperties[];\n activeTab: number;\n onSwitchTab: (index: number) => void;\n};\n\nconst TAB_SCROLL_THRESHOLD_PX = 16;\n\nconst TabList: FC = ({ tabs, activeTab, onSwitchTab }) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const previousActiveTab = usePrevious(activeTab);\n\n useHorizontalScroll(containerRef);\n\n // Scroll container to place active tab in the center\n useEffect(() => {\n const container = containerRef.current!;\n if (container.scrollWidth <= container.offsetWidth) {\n return;\n }\n\n const activeTabElement = container.querySelector('.Tab.active') as HTMLElement | null;\n if (activeTabElement) {\n const newLeft = activeTabElement.offsetLeft - (container.offsetWidth / 2) + (activeTabElement.offsetWidth / 2);\n\n // Prevent scrolling by only a couple of pixels, which doesn't look smooth\n if (Math.abs(newLeft - container.scrollLeft) < TAB_SCROLL_THRESHOLD_PX) {\n return;\n }\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n }, [activeTab]);\n\n const lang = useLang();\n\n return (\n
\n {tabs.map((tab, i) => (\n \n ))}\n
\n );\n};\n\nexport default memo(TabList);\n","import { ApiError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding key.',\n // eslint-disable-next-line max-len\n CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n","import { useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { ApiChat, ApiUser } from '../api/types';\nimport { isChatArchived, getCanDeleteChat, isChatPrivate } from '../modules/helpers';\n\nexport default ({\n chat,\n privateChatUser,\n handleDelete,\n folderId,\n isPinned,\n}: {\n chat: ApiChat | undefined;\n privateChatUser: ApiUser | undefined;\n handleDelete: () => void;\n folderId?: number;\n isPinned?: boolean;\n}) => {\n const {\n toggleChatPinned,\n updateChatMutedState,\n toggleChatArchived,\n toggleChatUnread,\n } = getDispatch();\n\n return useMemo(() => {\n if (!chat) {\n return undefined;\n }\n\n const isChatWithSelf = privateChatUser && privateChatUser.isSelf;\n\n const actionUnreadMark = chat.unreadCount || chat.hasUnreadMark\n ? { title: 'Mark as Read', icon: 'readchats', handler: () => toggleChatUnread({ id: chat.id }) }\n : { title: 'Mark as Unread', icon: 'unread', handler: () => toggleChatUnread({ id: chat.id }) };\n\n const actionPin = isPinned\n ? { title: 'Unpin', icon: 'unpin', handler: () => toggleChatPinned({ id: chat.id, folderId }) }\n : { title: 'Pin', icon: 'pin', handler: () => toggleChatPinned({ id: chat.id, folderId }) };\n\n const actionMute = chat.isMuted\n ? { title: 'Unmute', icon: 'unmute', handler: () => updateChatMutedState({ chatId: chat.id, isMuted: false }) }\n : { title: 'Mute', icon: 'mute', handler: () => updateChatMutedState({ chatId: chat.id, isMuted: true }) };\n\n const actionArchive = isChatArchived(chat)\n ? { title: 'Unarchive', icon: 'unarchive', handler: () => toggleChatArchived({ id: chat.id }) }\n : { title: 'Archive', icon: 'archive', handler: () => toggleChatArchived({ id: chat.id }) };\n\n const actionDelete = {\n title: isChatPrivate(chat.id) ? 'Delete' : (getCanDeleteChat(chat) ? 'Delete and Leave' : 'Leave'),\n icon: 'delete',\n destructive: true,\n handler: handleDelete,\n };\n\n return [\n actionUnreadMark,\n actionPin,\n ...(!isChatWithSelf ? [\n actionMute,\n actionArchive,\n ] : []),\n actionDelete,\n ];\n }, [\n chat, privateChatUser, handleDelete, folderId, isPinned,\n toggleChatPinned, updateChatMutedState, toggleChatArchived, toggleChatUnread,\n ]);\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../api/types';\nimport { formatPastTimeShort } from '../../util/dateFormat';\nimport MessageOutgoingStatus from './MessageOutgoingStatus';\nimport './LastMessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n};\n\nconst LastMessageMeta: FC = ({ message, outgoingStatus }) => {\n return (\n
\n {outgoingStatus && (\n \n )}\n {formatPastTimeShort(message.date * 1000)}\n
\n );\n};\n\nexport default LastMessageMeta;\n","import React, { FC } from '../../lib/teact/teact';\n\nimport { ApiMessageOutgoingStatus } from '../../api/types';\n\nimport Transition from '../ui/Transition';\n\nimport './MessageOutgoingStatus.scss';\n\ntype OwnProps = {\n status: ApiMessageOutgoingStatus;\n};\n\nenum Keys {\n failed, pending, succeeded, read,\n}\n\nconst MessageOutgoingStatus: FC = ({ status }) => {\n return (\n
\n \n {() => (\n \n )}\n \n
\n );\n};\n\nexport default MessageOutgoingStatus;\n","import { useState, useEffect } from '../lib/teact/teact';\nimport { IAnchorPosition } from '../types';\n\nexport default (\n anchor: IAnchorPosition | undefined,\n getTriggerElement: () => HTMLElement | null,\n getRootElement: () => HTMLElement | null,\n getMenuElement: () => HTMLElement | null,\n extraPaddingX = 0,\n extraTopPadding = 0,\n) => {\n const [positionX, setPositionX] = useState<'right' | 'left'>('right');\n const [positionY, setPositionY] = useState<'top' | 'bottom'>('bottom');\n const [style, setStyle] = useState('');\n\n useEffect(() => {\n const triggerEl = getTriggerElement();\n if (!anchor || !triggerEl) {\n return;\n }\n\n let { x, y } = anchor;\n const emptyRect = {\n width: 0, left: 0, height: 0, top: 0,\n };\n\n const menuEl = getMenuElement();\n const rootEl = getRootElement();\n\n const triggerRect = triggerEl.getBoundingClientRect();\n const menuRect = menuEl ? { width: menuEl.offsetWidth, height: menuEl.offsetHeight } : emptyRect;\n const rootRect = rootEl ? rootEl.getBoundingClientRect() : emptyRect;\n\n if (x + menuRect.width + extraPaddingX < rootRect.width + rootRect.left) {\n setPositionX('left');\n x += 3;\n } else if (x - menuRect.width > 0) {\n setPositionX('right');\n x -= 3;\n } else {\n setPositionX('left');\n x = 16;\n }\n\n if (y + menuRect.height < rootRect.height + rootRect.top) {\n setPositionY('top');\n } else {\n setPositionY('bottom');\n\n if (y - menuRect.height < rootRect.top + extraTopPadding) {\n y = rootRect.top + extraTopPadding + menuRect.height;\n }\n }\n\n setStyle(`left: ${x - triggerRect.left}px; top: ${y - triggerRect.top}px;`);\n }, [\n anchor, extraPaddingX, extraTopPadding,\n getMenuElement, getRootElement, getTriggerElement,\n ]);\n\n return {\n positionX,\n positionY,\n style,\n };\n};\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\n\ntype ChildrenFn = () => any;\n\ntype OwnProps = {\n isOpen: boolean;\n isCustom?: boolean;\n id?: string;\n className?: string;\n onClick?: (e: React.MouseEvent) => void;\n children: ChildrenFn;\n};\n\nconst ShowTransition: FC = ({\n isOpen, isCustom, id, className, onClick, children,\n}) => {\n const { shouldRender, transitionClassNames } = useShowTransition(\n isOpen, undefined, undefined, isCustom ? false : undefined,\n );\n const prevIsOpen = usePrevious(isOpen);\n const prevChildren = usePrevious(children);\n const fromChildrenRef = useRef();\n\n if (prevIsOpen && !isOpen) {\n fromChildrenRef.current = prevChildren;\n }\n\n return (\n shouldRender && (\n
\n {isOpen ? children() : fromChildrenRef.current!()}\n
\n )\n );\n};\n\nexport default ShowTransition;\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { register } from '../util/audioPlayer';\nimport useEffectWithPrevDeps from './useEffectWithPrevDeps';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\nimport useOnChange from './useOnChange';\n\ntype Handler = (e: Event) => void;\n\nexport default (\n trackId: string,\n originalDuration: number, // Sometimes incorrect for voice messages\n src?: string,\n handlers?: Record,\n onInit?: (element: HTMLAudioElement) => void,\n shouldPlay = false,\n onForcePlay?: NoneToVoidFunction,\n noPlaylist = false,\n) => {\n // eslint-disable-next-line no-null/no-null\n const controllerRef = useRef>(null);\n\n const [isPlaying, setIsPlaying] = useState(false);\n let isPlayingSync = isPlaying;\n\n const [playProgress, setPlayProgress] = useState(0);\n\n useOnChange(() => {\n controllerRef.current = register(trackId, (eventName, e) => {\n switch (eventName) {\n case 'onPlay':\n setIsPlaying(true);\n break;\n case 'onPause':\n setIsPlaying(false);\n break;\n case 'onTimeUpdate': {\n const { proxy } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n setPlayProgress(proxy.currentTime / duration);\n break;\n }\n }\n\n if (handlers && handlers[eventName]) {\n handlers[eventName](e);\n }\n }, onForcePlay);\n\n const { proxy } = controllerRef.current!;\n\n if (!isPlaying && !proxy.paused) {\n setIsPlaying(true);\n isPlayingSync = true;\n }\n\n if (onInit) {\n onInit(proxy);\n }\n }, [trackId]);\n\n const {\n play, pause, setCurrentTime, proxy, destroy,\n } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n\n // RAF progress\n useEffect(() => {\n if (duration && !isSafariPatchInProgress(proxy)) {\n setPlayProgress(proxy.currentTime / duration);\n }\n }, [duration, playProgress, proxy]);\n\n // Cleanup\n useEffect(() => () => {\n destroy(noPlaylist);\n }, [destroy, noPlaylist]);\n\n // Autoplay once `src` is present\n useEffectWithPrevDeps(([prevShouldPlay, prevSrc]) => {\n if (prevShouldPlay === shouldPlay && src === prevSrc) {\n return;\n }\n\n // When paused by another player\n if (proxy.src && proxy.paused) {\n return;\n }\n\n if (shouldPlay && src && !isPlaying) {\n play(src);\n }\n }, [shouldPlay, src, isPlaying, play, proxy.src, proxy.paused]);\n\n const playPause = useCallback(() => {\n if (isPlaying) {\n pause();\n } else if (src) {\n play(src);\n }\n }, [src, pause, play, isPlaying]);\n\n return {\n isPlaying: isPlayingSync,\n playProgress,\n playPause,\n setCurrentTime,\n audioProxy: proxy,\n duration,\n };\n};\n","import { IS_SAFARI } from './environment';\nimport safePlay from './safePlay';\nimport { patchSafariProgressiveAudio, isSafariPatchInProgress } from './patchSafariProgressiveAudio';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { parseMessageKey } from '../modules/helpers';\n\ntype Handler = (eventName: string, e: Event) => void;\n\ninterface Track {\n audio: HTMLAudioElement;\n proxy: HTMLAudioElement;\n handlers: Handler[];\n onForcePlay?: NoneToVoidFunction;\n}\n\nconst tracks = new Map();\nlet queue: string[] = [];\n\nlet currentTrackId: string | undefined;\n\nfunction createAudio(trackId: string, onForcePlay?: NoneToVoidFunction) {\n const audio = new Audio();\n\n function handleEvent(eventName: string) {\n return (e: Event) => {\n if (!tracks.has(trackId)) {\n return;\n }\n\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n tracks.get(trackId)!.handlers.forEach((handler) => {\n handler(eventName, e);\n });\n };\n }\n\n audio.addEventListener('timeupdate', handleEvent('onTimeUpdate'));\n audio.addEventListener('play', handleEvent('onPlay'));\n audio.addEventListener('pause', handleEvent('onPause'));\n audio.addEventListener('loadstart', handleEvent('onLoadStart'));\n audio.addEventListener('loadeddata', handleEvent('onLoadedData'));\n audio.addEventListener('playing', handleEvent('onPlaying'));\n audio.addEventListener('ended', () => {\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n const nextTrackId = queue[queue.indexOf(trackId) + 1];\n if (!nextTrackId) {\n return;\n }\n\n if (!tracks.has(nextTrackId)) {\n // A bit hacky way to continue playlist when switching chat\n getDispatch().openAudioPlayer(parseMessageKey(nextTrackId));\n\n return;\n }\n\n const nextTrack = tracks.get(nextTrackId)!;\n\n if (nextTrack.onForcePlay) {\n nextTrack.onForcePlay();\n }\n\n currentTrackId = nextTrackId;\n\n if (nextTrack.audio.src) {\n safePlay(nextTrack.audio);\n }\n });\n\n return {\n audio,\n proxy: new Proxy(audio, {\n get: (origin, key: keyof HTMLAudioElement) => origin[key],\n }),\n handlers: [],\n onForcePlay,\n };\n}\n\nexport function stopCurrentAudio() {\n const currentTrack = currentTrackId && tracks.get(currentTrackId);\n if (currentTrack) {\n currentTrack.audio.pause();\n }\n}\n\nexport function register(trackId: string, handler: Handler, onForcePlay?: NoneToVoidFunction) {\n if (!tracks.has(trackId)) {\n tracks.set(trackId, createAudio(trackId, onForcePlay));\n\n if (!queue.includes(trackId)) {\n queue.push(trackId);\n }\n }\n\n const { audio, proxy, handlers } = tracks.get(trackId)!;\n\n handlers.push(handler);\n\n return {\n play(src: string) {\n if (currentTrackId && currentTrackId !== trackId) {\n tracks.get(currentTrackId)!.audio.pause();\n }\n\n currentTrackId = trackId;\n\n if (!audio.src) {\n audio.src = src;\n audio.preload = 'auto';\n\n if (src.includes('/progressive/') && IS_SAFARI) {\n patchSafariProgressiveAudio(audio);\n }\n }\n\n safePlay(audio);\n },\n\n pause() {\n if (currentTrackId === trackId) {\n audio.pause();\n }\n },\n\n setCurrentTime(time: number) {\n if (currentTrackId === trackId) {\n audio.currentTime = time;\n }\n },\n\n proxy,\n\n destroy(shouldRemoveFromQueue = false) {\n const track = tracks.get(trackId);\n if (!track) {\n return;\n }\n\n track.handlers = track.handlers.filter((h) => h !== handler);\n\n if (!track.handlers.length) {\n track.audio.pause();\n tracks.delete(trackId);\n\n if (shouldRemoveFromQueue) {\n queue = queue.filter((id) => id !== trackId);\n }\n\n if (trackId === currentTrackId) {\n currentTrackId = undefined;\n }\n }\n },\n };\n}\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n link.click();\n}\n","import { RefObject } from 'react';\nimport React, { FC, memo, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport buildClassName from '../../util/buildClassName';\nimport { formatMediaDateTime, formatPastTimeShort } from '../../util/dateFormat';\nimport { getColorFromExtension, getFileSizeString } from './helpers/documentInfo';\nimport { getDocumentThumbnailDimensions } from './helpers/mediaDimensions';\nimport renderText from './helpers/renderText';\n\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './File.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n name: string;\n extension?: string;\n size: number;\n timestamp?: number;\n sender?: string;\n thumbnailDataUri?: string;\n previewData?: string;\n className?: string;\n smaller?: boolean;\n isTransferring?: boolean;\n isUploading?: boolean;\n isSelectable?: boolean;\n isSelected?: boolean;\n transferProgress?: number;\n onClick?: () => void;\n onDateClick?: (e: React.MouseEvent) => void;\n};\n\nconst File: FC = ({\n ref,\n name,\n size,\n extension = '',\n timestamp,\n sender,\n thumbnailDataUri,\n previewData,\n className,\n smaller,\n isTransferring,\n isUploading,\n isSelectable,\n isSelected,\n transferProgress,\n onClick,\n onDateClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, true);\n const color = getColorFromExtension(extension);\n const sizeString = getFileSizeString(size);\n\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewData, 'slow');\n const { width, height } = getDocumentThumbnailDimensions(smaller);\n\n const fullClassName = buildClassName(\n 'File',\n className,\n smaller && 'smaller',\n onClick && !isUploading && 'interactive',\n isSelected && 'file-is-selected',\n );\n\n return (\n
\n {isSelectable && (\n
\n {isSelected && }\n
\n )}\n
\n {thumbnailDataUri || previewData ? (\n
\n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n
\n ) : (\n
\n {extension.length <= 4 && (\n {extension}\n )}\n
\n )}\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {onClick && }\n
\n
\n
{renderText(name)}
\n
\n \n {isTransferring && transferProgress ? `${Math.round(transferProgress * 100)}%` : sizeString}\n \n {sender && {renderText(sender)}}\n {!sender && timestamp && (\n <>\n {' '}\n {formatMediaDateTime(timestamp * 1000)}\n \n )}\n
\n
\n {sender && timestamp && (\n {formatPastTimeShort(timestamp * 1000)}\n )}\n
\n );\n};\n\nexport default memo(File);\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-cond-assign */\n/* eslint-disable no-param-reassign */\n/* eslint-disable prefer-const */\n/* eslint-disable eqeqeq */\n\n/*\nSuperfast Blur - a fast Box Blur For Canvas\n\nVersion: 0.5\nAuthor: Mario Klingemann\nContact: mario@quasimondo.com\nWebsite: http://www.quasimondo.com/BoxBlurForCanvas\nTwitter: @quasimondo\n\nIn case you find this class useful - especially in commercial projects -\nI am not totally unhappy for a small donation to my PayPal account\nmario@quasimondo.de\n\nOr support me on flattr:\nhttps://flattr.com/thing/140066/Superfast-Blur-a-pretty-fast-Box-Blur-Effect-for-CanvasJavascript\n\nCopyright (c) 2011 Mario Klingemann\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// eslint-disable-next-line max-len\nconst mul_table = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];\n// eslint-disable-next-line max-len\nconst shg_table = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];\n\nexport default function boxBlurCanvasRGB(context, top_x, top_y, width, height, radius, iterations) {\n if (Number.isNaN(radius) || radius < 1) return;\n\n radius |= 0;\n\n if (Number.isNaN(iterations)) iterations = 1;\n iterations |= 0;\n if (iterations > 3) iterations = 3;\n if (iterations < 1) iterations = 1;\n\n const imageData = context.getImageData(top_x, top_y, width, height);\n\n const pixels = imageData.data;\n\n let rsum;\n let gsum;\n let bsum;\n let x;\n let y;\n let i;\n let p;\n let p1;\n let p2;\n let yp;\n let yi;\n let yw;\n let wm = width - 1;\n let hm = height - 1;\n let rad1 = radius + 1;\n\n let r = [];\n let g = [];\n let b = [];\n\n let mul_sum = mul_table[radius];\n let shg_sum = shg_table[radius];\n\n let vmin = [];\n let vmax = [];\n\n while (iterations-- > 0) {\n yw = yi = 0;\n\n for (y = 0; y < height; y++) {\n rsum = pixels[yw] * rad1;\n gsum = pixels[yw + 1] * rad1;\n bsum = pixels[yw + 2] * rad1;\n\n for (i = 1; i <= radius; i++) {\n p = yw + (((i > wm ? wm : i)) << 2);\n rsum += pixels[p++];\n gsum += pixels[p++];\n bsum += pixels[p++];\n }\n\n for (x = 0; x < width; x++) {\n r[yi] = rsum;\n g[yi] = gsum;\n b[yi] = bsum;\n\n if (y == 0) {\n vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;\n vmax[x] = ((p = x - radius) > 0 ? p << 2 : 0);\n }\n\n p1 = yw + vmin[x];\n p2 = yw + vmax[x];\n\n rsum += pixels[p1++] - pixels[p2++];\n gsum += pixels[p1++] - pixels[p2++];\n bsum += pixels[p1++] - pixels[p2++];\n\n yi++;\n }\n yw += (width << 2);\n }\n\n for (x = 0; x < width; x++) {\n yp = x;\n rsum = r[yp] * rad1;\n gsum = g[yp] * rad1;\n bsum = b[yp] * rad1;\n\n for (i = 1; i <= radius; i++) {\n yp += (i > hm ? 0 : width);\n rsum += r[yp];\n gsum += g[yp];\n bsum += b[yp];\n }\n\n yi = x << 2;\n for (y = 0; y < height; y++) {\n pixels[yi] = (rsum * mul_sum) >>> shg_sum;\n pixels[yi + 1] = (gsum * mul_sum) >>> shg_sum;\n pixels[yi + 2] = (bsum * mul_sum) >>> shg_sum;\n\n if (x == 0) {\n vmin[y] = ((p = y + rad1) < hm ? p : hm) * width;\n vmax[y] = ((p = y - radius) > 0 ? p * width : 0);\n }\n\n p1 = x + vmin[y];\n p2 = x + vmax[y];\n\n rsum += r[p1] - r[p2];\n gsum += g[p1] - g[p2];\n bsum += b[p1] - b[p2];\n\n yi += width << 2;\n }\n }\n }\n\n context.putImageData(imageData, top_x, top_y);\n}\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../lib/teact/teact';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport buildClassName from '../../util/buildClassName';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\n\nimport Portal from './Portal';\n\nimport './Notification.scss';\n\ntype OwnProps = {\n message: TextPart[];\n duration?: number;\n onDismiss: () => void;\n};\n\nconst DEFAULT_DURATION = 3000;\nconst ANIMATION_DURATION = 150;\n\nconst Notification: FC = ({ message, duration = DEFAULT_DURATION, onDismiss }) => {\n const [isOpen, setIsOpen] = useState(true);\n // eslint-disable-next-line no-null/no-null\n const timerRef = useRef(null);\n\n const { transitionClassNames } = useShowTransition(isOpen);\n\n const closeAndDismiss = useCallback(() => {\n setIsOpen(false);\n setTimeout(onDismiss, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [onDismiss]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(closeAndDismiss) : undefined), [isOpen, closeAndDismiss]);\n\n useEffect(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n\n return () => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n };\n }, [duration, closeAndDismiss]);\n\n const handleMouseEnter = useCallback(() => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n }, [duration, closeAndDismiss]);\n\n return (\n \n \n
\n {message}\n
\n
\n \n );\n};\n\nexport default memo(Notification);\n","import { EDITABLE_INPUT_ID } from '../../../../config';\n\nconst MAX_NESTING_PARENTS = 5;\n\nexport function isSelectionInsideInput(selectionRange: Range) {\n const { commonAncestorContainer } = selectionRange;\n let parentNode: HTMLElement | null = commonAncestorContainer as HTMLElement;\n let iterations = 1;\n while (parentNode && parentNode.id !== EDITABLE_INPUT_ID && iterations < MAX_NESTING_PARENTS) {\n parentNode = parentNode.parentElement;\n iterations++;\n }\n\n return Boolean(parentNode && parentNode.id === EDITABLE_INPUT_ID);\n}\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useEffect, useRef, memo, useState, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { IAnchorPosition, ISettings } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { selectCurrentMessageList, selectReplyingToId } from '../../../modules/selectors';\nimport { debounce } from '../../../util/schedulers';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport {\n IS_ANDROID, IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport useLayoutEffectWithPrevDeps from '../../../hooks/useLayoutEffectWithPrevDeps';\nimport useFlag from '../../../hooks/useFlag';\nimport parseEmojiOnlyString from '../../common/helpers/parseEmojiOnlyString';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport TextFormatter from './TextFormatter';\n\nconst CONTEXT_MENU_CLOSE_DELAY_MS = 100;\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 350;\nconst TRANSITION_DURATION_FACTOR = 50;\n\ntype OwnProps = {\n id: string;\n editableInputId?: string;\n html: string;\n placeholder: string;\n shouldSetFocus: boolean;\n shouldSupressFocus?: boolean;\n onUpdate: (html: string) => void;\n onSupressedFocus?: () => void;\n onSend: () => void;\n};\n\ntype StateProps = {\n currentChatId?: number;\n replyingToId?: number;\n noTabCapture?: boolean;\n messageSendKeyCombo?: ISettings['messageSendKeyCombo'];\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_INPUT_HEIGHT = IS_MOBILE_SCREEN ? 256 : 416;\nconst TAB_INDEX_PRIORITY_TIMEOUT = 2000;\nconst TEXT_FORMATTER_SAFE_AREA_PX = 90;\n// For some reason Safari inserts `
` after user removes text from input\nconst SAFARI_BR = '
';\n\nfunction clearSelection() {\n const selection = window.getSelection();\n if (!selection) {\n return;\n }\n\n if (selection.removeAllRanges) {\n selection.removeAllRanges();\n } else if (selection.empty) {\n selection.empty();\n }\n}\n\nconst MessageInput: FC = ({\n id,\n editableInputId,\n html,\n placeholder,\n shouldSetFocus,\n shouldSupressFocus,\n onUpdate,\n onSupressedFocus,\n onSend,\n currentChatId,\n replyingToId,\n noTabCapture,\n messageSendKeyCombo,\n editLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const cloneRef = useRef(null);\n\n const isContextMenuOpenRef = useRef(false);\n const [isTextFormatterOpen, openTextFormatter, closeTextFormatter] = useFlag();\n const [textFormatterAnchorPosition, setTextFormatterAnchorPosition] = useState();\n const [selectedRange, setSelectedRange] = useState();\n\n useLayoutEffectWithPrevDeps(([prevHtml]) => {\n if (html !== inputRef.current!.innerHTML) {\n inputRef.current!.innerHTML = html;\n }\n\n if (html !== cloneRef.current!.innerHTML) {\n cloneRef.current!.innerHTML = html;\n }\n\n if (prevHtml !== undefined && prevHtml !== html) {\n updateInputHeight(!html.length);\n }\n }, [html]);\n\n const focusInput = useCallback(() => {\n // Avoid focusing during animation\n if (inputRef.current!.closest('.from, .to')) {\n setTimeout(focusInput, FOCUS_DELAY_MS);\n return;\n }\n\n focusEditableElement(inputRef.current!);\n }, []);\n\n const handleCloseTextFormatter = useCallback(() => {\n closeTextFormatter();\n clearSelection();\n }, [closeTextFormatter]);\n\n function checkSelection() {\n // Disable the formatter on iOS devices for now.\n if (IS_IOS) {\n return;\n }\n\n const selection = window.getSelection();\n if (!selection || !selection.rangeCount || isContextMenuOpenRef.current) {\n closeTextFormatter();\n return;\n }\n\n const selectionRange = selection.getRangeAt(0);\n const selectedText = selectionRange.toString().trim();\n if (\n !isSelectionInsideInput(selectionRange)\n || !selectedText\n || parseEmojiOnlyString(selectedText)\n || !selectionRange.START_TO_END\n ) {\n closeTextFormatter();\n return;\n }\n\n const selectionRect = selectionRange.getBoundingClientRect();\n const inputRect = inputRef.current!.getBoundingClientRect();\n\n let x = (selectionRect.left + selectionRect.width / 2) - inputRect.left;\n\n if (x < TEXT_FORMATTER_SAFE_AREA_PX) {\n x = TEXT_FORMATTER_SAFE_AREA_PX;\n } else if (x > inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX) {\n x = inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX;\n }\n\n setTextFormatterAnchorPosition({\n x,\n y: selectionRect.top - inputRect.top,\n });\n\n setSelectedRange(selectionRange);\n openTextFormatter();\n }\n\n function handleMouseDown(event: React.MouseEvent) {\n function handleMouseUp() {\n checkSelection();\n\n event.target.removeEventListener('mouseup', handleMouseUp);\n }\n\n if (event.button !== 2) {\n event.target.addEventListener('mouseup', handleMouseUp);\n return;\n }\n\n if (isContextMenuOpenRef.current === true) {\n return;\n }\n\n isContextMenuOpenRef.current = true;\n\n function closeContextMenuMouseListener() {\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('mouseup', closeContextMenuMouseListener);\n }\n\n function closeContextMenuKeyListener(e: KeyboardEvent) {\n if (e.key !== 'Esc' && e.key !== 'Escape') {\n return;\n }\n\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('keydown', closeContextMenuKeyListener);\n }\n\n document.addEventListener('mousedown', closeContextMenuMouseListener);\n document.addEventListener('keydown', closeContextMenuKeyListener);\n }\n\n function handleKeyDown(e: React.KeyboardEvent) {\n function handleKeyUp() {\n checkSelection();\n\n e.target.removeEventListener('keyup', handleKeyUp);\n }\n\n if (e.key === 'Enter' && !e.shiftKey) {\n if (\n !(IS_IOS || IS_ANDROID)\n && (\n (messageSendKeyCombo === 'enter' && !e.shiftKey)\n || (messageSendKeyCombo === 'ctrl-enter' && (e.ctrlKey || e.metaKey))\n )\n ) {\n e.preventDefault();\n\n closeTextFormatter();\n onSend();\n }\n } else if (e.key === 'ArrowUp' && !html.length) {\n e.preventDefault();\n editLastMessage();\n } else {\n e.target.addEventListener('keyup', handleKeyUp);\n }\n }\n\n function handleTouchSelection() {\n if (!IS_ANDROID) {\n return;\n }\n\n checkSelection();\n }\n\n function handleChange(e: ChangeEvent) {\n const { innerHTML, textContent } = e.currentTarget;\n\n onUpdate(innerHTML === SAFARI_BR ? '' : innerHTML);\n\n // Reset focus on the input to remove any active styling when input is cleared\n if (!IS_TOUCH_ENV && (!textContent || !textContent.length)) {\n const selection = window.getSelection()!;\n if (selection) {\n inputRef.current!.blur();\n selection.removeAllRanges();\n focusEditableElement(inputRef.current!, true);\n }\n }\n }\n\n function stopEvent(e: React.MouseEvent) {\n if (!IS_ANDROID) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n }\n\n function updateInputHeight(willSend = false) {\n const input = inputRef.current!;\n const clone = cloneRef.current!;\n const currentHeight = Number(input.style.height.replace('px', ''));\n const newHeight = Math.min(clone.scrollHeight, MAX_INPUT_HEIGHT);\n if (newHeight === currentHeight) {\n return;\n }\n\n const transitionDuration = Math.round(\n TRANSITION_DURATION_FACTOR * Math.log(Math.abs(newHeight - currentHeight)),\n );\n\n const exec = () => {\n input.style.height = `${newHeight}px`;\n input.style.transitionDuration = `${transitionDuration}ms`;\n input.classList.toggle('overflown', clone.scrollHeight > MAX_INPUT_HEIGHT);\n };\n\n if (willSend) {\n // Sync with sending animation\n requestAnimationFrame(exec);\n } else {\n exec();\n }\n }\n\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n focusInput();\n }, [currentChatId, focusInput, replyingToId, shouldSetFocus]);\n\n useEffect(() => {\n if (noTabCapture) {\n return undefined;\n }\n\n const captureFirstTab = debounce((e: KeyboardEvent) => {\n if (e.key === 'Tab') {\n e.preventDefault();\n requestAnimationFrame(focusInput);\n }\n }, TAB_INDEX_PRIORITY_TIMEOUT, true, false);\n\n return captureKeyboardListeners({ onTab: captureFirstTab });\n }, [focusInput, noTabCapture]);\n\n useEffect(() => {\n const input = inputRef.current!;\n\n function supressFocus() {\n input.blur();\n }\n\n if (shouldSupressFocus) {\n input.addEventListener('focus', supressFocus);\n }\n\n return () => {\n input.removeEventListener('focus', supressFocus);\n };\n }, [shouldSupressFocus]);\n\n const className = buildClassName(\n 'form-control custom-scroll',\n html.length > 0 && 'touched',\n shouldSupressFocus && 'focus-disabled',\n );\n\n return (\n
\n \n
\n {placeholder}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: currentChatId, threadId } = selectCurrentMessageList(global) || {};\n const { messageSendKeyCombo } = global.settings.byKey;\n\n return {\n currentChatId,\n messageSendKeyCombo,\n replyingToId: currentChatId && threadId ? selectReplyingToId(global, currentChatId, threadId) : undefined,\n noTabCapture: global.isPollModalOpen || global.payment.isPaymentModalOpen,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editLastMessage']),\n)(MessageInput));\n","import { useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport useOnChange from './useOnChange';\nimport useBlur from './useBlur';\nimport { imgToCanvas } from '../util/files';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\n\nexport default function useBlurSync(dataUri: string | false | undefined) {\n const blurredRef = useRef();\n\n let isChanged = false;\n\n useOnChange(() => {\n isChanged = true;\n\n blurredRef.current = undefined;\n\n if (!dataUri) {\n return;\n }\n\n const img = new Image();\n img.src = dataUri;\n if (!img.width) {\n return;\n }\n\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n\n blurredRef.current = canvas.toDataURL();\n }, [dataUri]);\n\n // Sometimes `Image` do not manage to load synchronously,\n // so we fall back the non-blurred variant and prepare the async one at least for the next time\n const blurredAsync = useBlur(dataUri || undefined, Boolean(blurredRef.current));\n\n return blurredRef.current || (!isChanged && blurredAsync) || dataUri || undefined;\n}\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiWebPage } from '../../api/types';\n\nimport { getFirstLinkInMessage, getMessageSummaryText, getMessageWebPage } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport trimText from '../../util/trimText';\nimport renderText from './helpers/renderText';\nimport { formatPastTimeShort } from '../../util/dateFormat';\n\nimport Media from './Media';\nimport Link from '../ui/Link';\nimport SafeLink from './SafeLink';\n\nimport './WebLink.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n onMessageClick: (messageId: number, chatId: number) => void;\n};\n\nconst WebLink: FC = ({ message, senderTitle, onMessageClick }) => {\n let linkData: ApiWebPage | undefined = getMessageWebPage(message);\n\n if (!linkData) {\n const link = getFirstLinkInMessage(message);\n if (link) {\n const { url, domain } = link;\n const messageText = getMessageSummaryText(message);\n\n linkData = {\n siteName: domain.replace(/^www./, ''),\n url: url.includes('://') ? url : url.includes('@') ? `mailto:${url}` : `http://${url}`,\n description: messageText !== url ? messageText : undefined,\n } as ApiWebPage;\n }\n }\n\n const handleMessageClick = useCallback(() => {\n onMessageClick(message.id, message.chatId);\n }, [onMessageClick, message.id, message.chatId]);\n\n if (!linkData) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = linkData;\n\n const truncatedDescription = !senderTitle && trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebLink scroll-item',\n !photo && 'without-photo',\n );\n\n return (\n \n {photo && (\n \n )}\n
\n {renderText(title || siteName || displayUrl)}\n {truncatedDescription && (\n {renderText(truncatedDescription)}\n )}\n \n {url.replace('mailto:', '') || displayUrl}\n \n {senderTitle &&
{renderText(senderTitle)}
}\n
\n {senderTitle && (\n
\n \n {formatPastTimeShort(message.date * 1000)}\n \n
\n )}\n
\n );\n};\n\nexport default memo(WebLink);\n","import { useCallback } from '../../../../lib/teact/teact';\n\nexport enum ChatAnimationTypes {\n Move,\n Opacity,\n None,\n}\n\nexport function useChatAnimationType(orderDiffById: Record) {\n const movesUp = useCallback((id: number) => orderDiffById[id] < 0, [orderDiffById]);\n const movesDown = useCallback((id: number) => orderDiffById[id] > 0, [orderDiffById]);\n\n const orderDiffIds = Object.keys(orderDiffById).map(Number);\n const numberOfUp = orderDiffIds.filter(movesUp).length;\n const numberOfDown = orderDiffIds.filter(movesDown).length;\n\n return useCallback((chatId: number): ChatAnimationTypes => {\n const orderDiff = orderDiffById[chatId];\n\n if (orderDiff === 0) {\n return ChatAnimationTypes.None;\n }\n\n if (\n orderDiff === Infinity\n || orderDiff === -Infinity\n || (movesUp(chatId) && numberOfUp <= numberOfDown)\n || (movesDown(chatId) && numberOfDown < numberOfUp)\n ) {\n return ChatAnimationTypes.Opacity;\n }\n\n return ChatAnimationTypes.Move;\n }, [movesDown, movesUp, numberOfDown, numberOfUp, orderDiffById]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\n\nimport ShowTransition from '../../ui/ShowTransition';\n\nimport './Badge.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n isPinned?: boolean;\n};\n\nconst Badge: FC = ({ chat, isPinned }) => {\n const isShown = Boolean(chat.unreadCount || chat.hasUnreadMark || isPinned);\n const className = buildClassName(\n 'Badge',\n chat.isMuted && 'muted',\n isPinned && 'pinned',\n Boolean(chat.unreadCount || chat.hasUnreadMark) && 'unread',\n );\n\n function renderContent() {\n if (chat.unreadCount) {\n if (chat.unreadMentionsCount) {\n return (\n
\n
\n \n
\n
\n {formatIntegerCompact(chat.unreadCount)}\n
\n
\n );\n }\n\n return (\n
\n {formatIntegerCompact(chat.unreadCount)}\n
\n );\n } else if (chat.hasUnreadMark) {\n return (\n
\n );\n } else if (isPinned) {\n return (\n
\n \n
\n );\n }\n\n return undefined;\n }\n\n return (\n \n {renderContent}\n \n );\n};\n\nexport default Badge;\n","import React, {\n FC, memo, useCallback, useLayoutEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport useLang from '../../../hooks/useLang';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus, ApiFormattedText, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n isChatPrivate,\n isActionMessage,\n getPrivateChatUserId,\n getMessageAction,\n getMessageSenderName,\n isChatChannel,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageSticker,\n} from '../../../modules/helpers';\nimport {\n selectChat, selectUser, selectChatMessage, selectOutgoingStatus, selectDraft, selectCurrentMessageList,\n} from '../../../modules/selectors';\nimport { renderActionMessageText } from '../../common/helpers/renderActionMessageText';\nimport renderText from '../../common/helpers/renderText';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport useMedia from '../../../hooks/useMedia';\nimport { ChatAnimationTypes } from './hooks';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport TypingStatus from '../../common/TypingStatus';\nimport LastMessageMeta from '../../common/LastMessageMeta';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\nimport Badge from './Badge';\n\nimport './Chat.scss';\n\ntype OwnProps = {\n style?: string;\n chatId: number;\n folderId?: number;\n orderDiff: number;\n animationType: ChatAnimationTypes;\n isSelected: boolean;\n isPinned?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n actionTargetUser?: ApiUser;\n actionTargetMessage?: ApiMessage;\n actionTargetChatId?: number;\n lastMessageSender?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n draft?: ApiFormattedText;\n messageListType?: MessageListType;\n animationLevel?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 200;\n\nconst Chat: FC = ({\n style,\n chatId,\n folderId,\n orderDiff,\n animationType,\n isSelected,\n isPinned,\n chat,\n privateChatUser,\n actionTargetUser,\n lastMessageSender,\n lastMessageOutgoingStatus,\n actionTargetMessage,\n actionTargetChatId,\n draft,\n messageListType,\n animationLevel,\n lastSyncTime,\n openChat,\n focusLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const { lastMessage, typingStatus } = chat || {};\n const isAction = lastMessage && isActionMessage(lastMessage);\n\n useEnsureMessage(chatId, isAction ? lastMessage!.replyToMessageId : undefined, actionTargetMessage);\n\n const mediaThumbnail = lastMessage && !getMessageSticker(lastMessage)\n ? getMessageMediaThumbDataUri(lastMessage)\n : undefined;\n const mediaBlobUrl = useMedia(lastMessage ? getMessageMediaHash(lastMessage, 'micro') : undefined);\n\n // Sets animation excess values when `orderDiff` changes and then resets excess values to animate.\n useLayoutEffect(() => {\n if (animationLevel === 0) {\n return;\n }\n\n const element = ref.current!;\n\n // TODO Refactor animation: create `useListAnimation` that owns `orderDiff` and `animationType`\n if (animationType === ChatAnimationTypes.Opacity) {\n element.style.opacity = '0';\n\n fastRaf(() => {\n element.classList.add('animate-opacity');\n element.style.opacity = '1';\n });\n } else if (animationType === ChatAnimationTypes.Move) {\n element.style.transform = `translate3d(0, ${-orderDiff * 100}%, 0)`;\n\n fastRaf(() => {\n element.classList.add('animate-transform');\n element.style.transform = '';\n });\n } else {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n element.classList.remove('animate-opacity', 'animate-transform');\n element.style.opacity = '';\n element.style.transform = '';\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [animationLevel, orderDiff, animationType]);\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId });\n\n if (isSelected && messageListType === 'thread') {\n focusLastMessage();\n }\n }, [\n isSelected,\n messageListType,\n openChat,\n chatId,\n focusLastMessage,\n ]);\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n handleDelete: openDeleteModal,\n folderId,\n isPinned,\n });\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderLastMessageOrTyping() {\n if (typingStatus && lastMessage && typingStatus.timestamp > lastMessage.date * 1000) {\n return ;\n }\n\n if (draft && draft.text.length) {\n return (\n

\n {lang('Draft')}\n {renderText(draft.text)}\n

\n );\n }\n\n if (!lastMessage) {\n return undefined;\n }\n\n if (isAction) {\n const actionOrigin = chat && (isChatChannel(chat) || lastMessage.senderId === lastMessage.chatId)\n ? chat\n : lastMessageSender;\n\n return (\n

\n {renderText(renderActionMessageText(\n lastMessage,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string)}\n

\n );\n }\n\n const senderName = getMessageSenderName(chatId, lastMessageSender);\n\n return (\n

\n {senderName && (\n {renderText(senderName)}\n )}\n {renderMessageSummary(lastMessage!, mediaBlobUrl || mediaThumbnail)}\n

\n );\n }\n\n const className = buildClassName(\n 'Chat chat-item-clickable',\n isChatPrivate(chatId) ? 'private' : 'group',\n isSelected && !IS_MOBILE_SCREEN && 'selected',\n );\n\n return (\n \n \n
\n
\n

{renderText(getChatTitle(chat, privateChatUser))}

\n {chat.isVerified && }\n {chat.isMuted && }\n {chat.lastMessage && (\n \n )}\n
\n
\n {renderLastMessageOrTyping()}\n \n
\n
\n \n \n );\n};\n\nfunction renderMessageSummary(message: ApiMessage, blobUrl?: string) {\n if (!blobUrl) {\n return renderText(getMessageSummaryText(message));\n }\n\n return (\n \n \"\"\n {getMessageVideo(message) && }\n {renderText(getMessageSummaryText(message, true))}\n \n );\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return {};\n }\n\n const { senderId, replyToMessageId, isOutgoing } = chat.lastMessage;\n const lastMessageSender = senderId ? selectUser(global, senderId) : undefined;\n const lastMessageAction = getMessageAction(chat.lastMessage);\n const actionTargetMessage = lastMessageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const { targetUserId: actionTargetUserId, targetChatId: actionTargetChatId } = lastMessageAction || {};\n const privateChatUserId = getPrivateChatUserId(chat);\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n\n return {\n chat,\n lastMessageSender,\n ...(isOutgoing && { lastMessageOutgoingStatus: selectOutgoingStatus(global, chat.lastMessage) }),\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n ...(actionTargetUserId && { actionTargetUser: selectUser(global, actionTargetUserId) }),\n actionTargetChatId,\n actionTargetMessage,\n draft: selectDraft(global, chatId, MAIN_THREAD_ID),\n messageListType,\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'focusLastMessage',\n ]),\n)(Chat));\n","import React, {\n FC, memo, useMemo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiChatFolder, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { ALL_CHATS_PRELOAD_DISABLED, CHAT_HEIGHT_PX, CHAT_LIST_SLICE } from '../../../config';\nimport { IS_ANDROID } from '../../../util/environment';\nimport usePrevious from '../../../hooks/usePrevious';\nimport { mapValues, pick } from '../../../util/iteratees';\nimport { getChatOrder, prepareChatList, prepareFolderListIds } from '../../../modules/helpers';\nimport { selectChatFolder, selectCurrentMessageList } from '../../../modules/selectors';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\nimport { useChatAnimationType } from './hooks';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Loading from '../../ui/Loading';\nimport Chat from './Chat';\n\ntype OwnProps = {\n folderType: 'all' | 'archived' | 'folder';\n folderId?: number;\n noChatsText?: string;\n};\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFolder?: ApiChatFolder;\n listIds?: number[];\n currentChatId?: number;\n orderedPinnedIds?: number[];\n lastSyncTime?: number;\n isInDiscussionThread?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nenum FolderTypeToListType {\n 'all' = 'active',\n 'archived' = 'archived'\n}\n\nconst ChatList: FC = ({\n folderType,\n folderId,\n noChatsText = 'Chat list is empty.',\n chatFolder,\n chatsById,\n usersById,\n listIds,\n currentChatId,\n orderedPinnedIds,\n lastSyncTime,\n isInDiscussionThread,\n loadMoreChats,\n preloadTopChatMessages,\n}) => {\n const [currentListIds, currentPinnedIds] = useMemo(() => {\n return folderType === 'folder' && chatFolder\n ? prepareFolderListIds(chatsById, usersById, chatFolder)\n : [listIds, orderedPinnedIds];\n }, [folderType, chatsById, usersById, chatFolder, listIds, orderedPinnedIds]);\n\n const [orderById, orderedIds] = useMemo(() => {\n if (!currentListIds || (folderType === 'folder' && !chatFolder)) {\n return [];\n }\n const newChatArrays = prepareChatList(chatsById, currentListIds, currentPinnedIds, folderType);\n const singleList = [...newChatArrays.pinnedChats, ...newChatArrays.otherChats];\n const newOrderedIds = singleList.map(({ id }) => id);\n const newOrderById = singleList.reduce((acc, chat, i) => {\n acc[chat.id] = i;\n return acc;\n }, {} as Record);\n\n return [newOrderById, newOrderedIds];\n }, [currentListIds, currentPinnedIds, folderType, chatFolder, chatsById]);\n\n const prevOrderById = usePrevious(orderById);\n\n const orderDiffById = orderById && prevOrderById\n ? mapValues(orderById, (order, id) => {\n return order - (prevOrderById[id] !== undefined ? prevOrderById[id] : Infinity);\n })\n : {};\n\n const loadMoreOfType = useCallback(() => {\n loadMoreChats({ listType: folderType === 'archived' ? 'archived' : 'active' });\n }, [loadMoreChats, folderType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? loadMoreOfType : undefined,\n orderedIds,\n undefined,\n CHAT_LIST_SLICE,\n folderType === 'all' && !ALL_CHATS_PRELOAD_DISABLED,\n );\n\n // TODO Refactor to not call `prepareChatList` twice\n const chatArrays = viewportIds && prepareChatList(chatsById, viewportIds, currentPinnedIds, folderType);\n\n useEffect(() => {\n if (lastSyncTime && folderType === 'all') {\n preloadTopChatMessages();\n }\n }, [lastSyncTime, folderType, preloadTopChatMessages]);\n\n const getAnimationType = useChatAnimationType(orderDiffById);\n\n function renderChats() {\n const viewportOffset = orderedIds!.indexOf(viewportIds![0]);\n const pinnedOffset = viewportOffset + chatArrays!.pinnedChats.length;\n\n return (\n \n {chatArrays!.pinnedChats.map(({ id }, i) => (\n \n ))}\n {chatArrays!.otherChats.map((chat, i) => (\n \n ))}\n
\n );\n }\n\n return (\n \n {viewportIds && viewportIds.length && chatArrays ? (\n renderChats()\n ) : viewportIds && !viewportIds.length ? (\n
{noChatsText}
\n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { folderType, folderId }): StateProps => {\n const {\n chats: {\n listIds,\n byId: chatsById,\n orderedPinnedIds,\n },\n users: { byId: usersById },\n lastSyncTime,\n } = global;\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n const listType = folderType !== 'folder' ? FolderTypeToListType[folderType] : undefined;\n const chatFolder = folderId ? selectChatFolder(global, folderId) : undefined;\n\n return {\n chatsById,\n usersById,\n currentChatId,\n lastSyncTime,\n ...(listType ? {\n listIds: listIds[listType],\n orderedPinnedIds: orderedPinnedIds[listType],\n } : {\n chatFolder,\n }),\n isInDiscussionThread: currentThreadId !== MAIN_THREAD_ID,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMoreChats', 'preloadTopChatMessages']),\n)(ChatList));\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","import { useCallback, useEffect, useState } from '../../../../lib/teact/teact';\n\nimport { ApiMessageEntityTypes, ApiChatMember, ApiUser } from '../../../../api/types';\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport { getUserFirstOrLastName } from '../../../../modules/helpers';\nimport searchUserName from '../helpers/searchUserName';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst RE_NOT_USERNAME_SEARCH = /[^@_\\d\\wа-яё]+/i;\n\nexport default function useMentionMenu(\n canSuggestMembers: boolean | undefined,\n html: string,\n onUpdateHtml: (html: string) => void,\n inputId: string = EDITABLE_INPUT_ID,\n groupChatMembers?: ApiChatMember[],\n currentUserId?: number,\n usersById?: Record,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [currentFilter, setCurrentFilter] = useState('');\n const [filteredMembers, setFilteredMembers] = useState([]);\n\n const getFilteredMembers = useCallback((filter) => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return groupChatMembers.filter(({ userId }) => {\n const user = usersById[userId];\n if (userId === currentUserId || !user) {\n return false;\n }\n\n return !filter || searchUserName(filter, user);\n });\n }, [groupChatMembers, currentUserId, usersById]);\n\n useEffect(() => {\n if (!canSuggestMembers || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const usernameFilter = getUsernameFilter(html);\n\n if (usernameFilter) {\n const filter = usernameFilter ? usernameFilter.substr(1) : '';\n const membersToMention = getFilteredMembers(filter);\n if (membersToMention && membersToMention.length) {\n markIsOpen();\n setCurrentFilter(filter);\n setFilteredMembers(membersToMention);\n } else {\n unmarkIsOpen();\n }\n } else {\n unmarkIsOpen();\n }\n }, [canSuggestMembers, html, getFilteredMembers, markIsOpen, unmarkIsOpen]);\n\n const insertMention = useCallback((user: ApiUser, forceFocus = false) => {\n if (!user.username && !getUserFirstOrLastName(user)) {\n return;\n }\n\n const insertedHtml = user.username\n ? `@${user.username}`\n : `${getUserFirstOrLastName(user)}`;\n\n const atIndex = html.lastIndexOf('@');\n if (atIndex !== -1) {\n onUpdateHtml(`${html.substr(0, atIndex)}${insertedHtml} `);\n const messageInput = document.getElementById(inputId)!;\n if (!IS_MOBILE_SCREEN) {\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, forceFocus);\n });\n }\n }\n\n unmarkIsOpen();\n }, [html, inputId, onUpdateHtml, unmarkIsOpen]);\n\n return {\n isMentionMenuOpen: isOpen,\n mentionFilter: currentFilter,\n closeMentionMenu: unmarkIsOpen,\n insertMention,\n mentionFilteredMembers: filteredMembers,\n };\n}\n\nfunction getUsernameFilter(html: string) {\n const tempEl = document.createElement('div');\n tempEl.innerHTML = html;\n const text = tempEl.innerText;\n\n const lastSymbol = text[text.length - 1];\n const lastWord = text.split(RE_NOT_USERNAME_SEARCH).pop();\n\n if (\n !text.length || RE_NOT_USERNAME_SEARCH.test(lastSymbol)\n || !lastWord || !lastWord.startsWith('@')\n ) {\n return undefined;\n }\n\n return lastWord;\n}\n","import { ApiUser } from '../../../../api/types';\nimport { getUserFullName } from '../../../../modules/helpers';\nimport searchWords from '../../../../util/searchWords';\n\n// TODO: Support cyrillic translit search\nexport default function searchUserName(filter: string, user: ApiUser) {\n const usernameLowered = user.username.toLowerCase();\n const fullName = getUserFullName(user);\n const fullNameLowered = fullName && fullName.toLowerCase();\n const filterLowered = filter.toLowerCase();\n\n return usernameLowered.startsWith(filterLowered) || (\n fullNameLowered && searchWords(fullNameLowered, filterLowered)\n );\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/2.28b104a90f1c1a985b2b.css b/dist/2.07f32bea8faa762b432b.css similarity index 100% rename from dist/2.28b104a90f1c1a985b2b.css rename to dist/2.07f32bea8faa762b432b.css diff --git a/dist/2.28b104a90f1c1a985b2b.js b/dist/2.07f32bea8faa762b432b.js similarity index 99% rename from dist/2.28b104a90f1c1a985b2b.js rename to dist/2.07f32bea8faa762b432b.js index a05ac32f..83a55b69 100644 --- a/dist/2.28b104a90f1c1a985b2b.js +++ b/dist/2.07f32bea8faa762b432b.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[2],Array(92).concat([function(e,t,a){"use strict";a.r(t),a.d(t,"MediaViewer",(function(){return de})),a.d(t,"ForwardPicker",(function(){return Oe})),a.d(t,"Errors",(function(){return ye})),a.d(t,"Notifications",(function(){return Ne})),a.d(t,"CalendarModal",(function(){return Pe})),a.d(t,"DeleteMessageModal",(function(){return Me})),a.d(t,"PinMessageModal",(function(){return Fe})),a.d(t,"UnpinAllMessagesModal",(function(){return Le})),a.d(t,"MessageSelectToolbar",(function(){return De})),a.d(t,"LeftSearch",(function(){return Ot})),a.d(t,"Settings",(function(){return cn})),a.d(t,"ContactList",(function(){return sn})),a.d(t,"NewChat",(function(){return un})),a.d(t,"NewChatStep1",(function(){return on})),a.d(t,"NewChatStep2",(function(){return dn})),a.d(t,"ArchivedChats",(function(){return bn})),a.d(t,"ContextMenuContainer",(function(){return In})),a.d(t,"StickerSetModal",(function(){return Sn})),a.d(t,"HeaderMenuContainer",(function(){return Pn})),a.d(t,"MobileSearch",(function(){return Ln})),a.d(t,"AttachmentModal",(function(){return zn})),a.d(t,"PollModal",(function(){return $n})),a.d(t,"SymbolMenu",(function(){return bc})),a.d(t,"AttachMenu",(function(){return pc})),a.d(t,"MentionMenu",(function(){return Gn})),a.d(t,"EmojiTooltip",(function(){return gc})),a.d(t,"BotKeyboardMenu",(function(){return vc})),a.d(t,"CustomSendMenu",(function(){return Ec})),a.d(t,"DropArea",(function(){return fc.b})),a.d(t,"TextFormatter",(function(){return Oc.a})),a.d(t,"RightSearch",(function(){return Cc})),a.d(t,"StickerSearch",(function(){return Ic})),a.d(t,"GifSearch",(function(){return Sc})),a.d(t,"PollResults",(function(){return Pc})),a.d(t,"Management",(function(){return Hc})),a.d(t,"PaymentModal",(function(){return pr})),a.d(t,"ReceiptModal",(function(){return Er}));var n=a(0),c=a(2),r=a(4),s=a(19),l=a(1),o=a(7),i=a(105),d=a(6),m=a(5),u=a(3),h=a(121),b=a(42),p=a(166),g=a(31),v=a(97),E=a(111),f=a(173),O=a(38),j=a(43),C=a(135),y=a(49);function k(e,t,a,n){const{mediaEl:c}=P(t,n);if(!c)return;const{width:r}=y.a.get();let o,d=!1;if(n){const{photo:e,video:t,webPage:a}=Object(m.v)(n);d=Boolean(t),o=t?Object(m.ab)(t):Object(m.R)(e||a.photo)}else o=i.a;const{width:u,height:h}=Object(i.j)(e,d),{width:b,height:p}=Object(i.e)(u,h,o.width,o.height),g=(r-b)/2,v=function(e){const t=window.matchMedia(i.b);let a=4.125;e&&(a+=t.matches?.875:3.375);return a*i.c}(e)+(h-p)/2;let{top:E,left:f,width:O,height:j}=c.getBoundingClientRect();if([s.h.SharedMedia,s.h.Album,s.h.ScheduledAlbum,s.h.SearchResult].includes(t)){const e=function(e,t,a,n,c,r){if(e===t){const s=Math.max(c,r)*(e/t);n-=(s-c)/2,a-=(s-r)/2,c=s,r=s}else if(e>t){const a=c;n-=((c=r*(e/t))-a)/2}else if(t>e){const n=r;a-=((r=c*(t/e))-n)/2}return{top:a,left:n,width:c,height:r}}(b,p,E,f,O,j);E=e.top,f=e.left,O=e.width,j=e.height}const C=f+O/2-(g+b/2),k=E+j/2-(v+p/2),N=O/b,S=j/p,F=I(a||c);w(F,{top:v+"px",left:g+"px",width:b+"px",height:p+"px",transform:`translate3d(${C}px, ${k}px, 0) scale(${N}, ${S})`}),M(F,t),document.body.classList.add("ghost-animating"),requestAnimationFrame(()=>{document.body.appendChild(F),requestAnimationFrame(()=>{F.style.transform="",function(e){e.firstChild.style.objectFit="default",e.classList.remove("rounded-corners","circle")}(F),setTimeout(()=>{requestAnimationFrame(()=>{document.body.removeChild(F),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function N(e,t,a){const{container:n,mediaEl:c}=P(e,a);if(!c)return;const r=document.getElementById("MediaViewer").querySelector(".active .media-viewer-content img, .active .media-viewer-content video");if(!r||!c)return;const{top:o,left:i,width:d,height:m}=r.getBoundingClientRect(),{top:u,left:h,width:b,height:p}=c.getBoundingClientRect();let g=u;if(!function(e){if("none"===e.style.display)return!1;const t=e.getBoundingClientRect(),{height:a}=y.a.get();return t.top<=a&&t.top+t.height>=0}(n)){const{height:e}=y.a.get();g=uO?f=O:O>f&&(O=f));const C=I(t||c,e===s.h.ProfileAvatar);w(C,{top:g+"px",left:h+"px",width:b+"px",height:p+"px",transform:`translate3d(${v}px, ${E}px, 0) scale(${f}, ${O})`}),requestAnimationFrame(()=>{document.body.classList.add("ghost-animating"),document.body.appendChild(C),requestAnimationFrame(()=>{C.style.transform="",j&&(C.style.opacity="0"),M(C,e),setTimeout(()=>{requestAnimationFrame(()=>{document.body.removeChild(C),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function I(e,t=!1){const a=document.createElement("div");a.classList.add("ghost");const n=new Image;if("string"==typeof e?n.src=e:e instanceof HTMLVideoElement?n.src=e.poster:n.src=e.src,a.appendChild(n),t){a.classList.add("ProfileInfo");const e=document.querySelector("#RightColumn .ProfileInfo .info");e&&a.appendChild(e.cloneNode(!0))}return a}function S(e,t){const a=document.querySelector(".active > .MessageList");let n=e.offsetTop+t.closest(".content-inner, .WebPage").offsetTop;return e.id.includes("album-media-")&&(n+=e.parentElement.offsetTop+e.closest(".Message").offsetTop),n>a.scrollTop&&n+t.offsetHeight{if(n&&t)return{sender:Object(m.kb)(t)?Object(d.Db)(e,t):Object(d.f)(e,t)};if(!a||!t)return{};const c=Object(d.k)(e,t,a);return{message:c,sender:c&&Object(d.qb)(e,c)}},(e,t)=>Object(u.l)(t,["closeMediaViewer","focusMessage"]))(({chatId:e,messageId:t,sender:a,isAvatar:c,message:r,closeMediaViewer:s,focusMessage:l})=>{const o=Object(n.m)(()=>{s(),l({chatId:e,messageId:t})},[e,l,t,s]);if(Object(F.a)(),!a||!r&&!c)return;const i=a.id<0,d=Object(m.U)(a);return n.a.createElement("div",{className:"SenderInfo",onClick:o},i?n.a.createElement(U.a,{key:a.id,size:"medium",chat:a}):n.a.createElement(U.a,{key:a.id,size:"medium",user:a}),n.a.createElement("div",{className:"meta"},n.a.createElement("div",{className:"title"},d&&Object(x.a)(d)),n.a.createElement("div",{className:"date"},c?"Profile photo":Object(D.d)(1e3*r.date))))}),G=a(167),z=a(56),q=a(34),$=a(112);a(243);var H=({mediaData:e,isVideo:t,isZoomed:a,message:c,fileName:r,isAvatar:s,onCloseMediaViewer:l,onForward:i,onZoomToggle:d})=>{const[u,h]=Object(n.r)(!1),b=t&&c?Object(m.D)(c,"download"):void 0,{mediaData:p,downloadProgress:g}=Object(E.a)(b,!u);Object(n.n)(()=>{u&&p&&(Object(G.a)(p,r),h(!1))},[r,p,u]),Object(n.n)(()=>{h(!1)},[b]);const v=Object(n.m)(e=>{e.stopPropagation(),h(e=>!e)},[]),f=Object(F.a)(),O=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",className:t?"active":void 0,onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]);return o.f?n.a.createElement("div",{className:"MediaViewerActions-mobile"},n.a.createElement(z.a,{trigger:O,positionX:"right"},!s&&n.a.createElement(q.a,{icon:"forward",onClick:i},f("Forward")),t?n.a.createElement(q.a,{icon:u?"close":"download",onClick:v},u?Math.round(100*g)+"% Downloading...":"Download"):n.a.createElement(q.a,{icon:"download",href:e,download:r},f("AccActionDownload"))),u&&n.a.createElement($.a,{progress:g,size:"s",noCross:!0})):n.a.createElement("div",{className:"MediaViewerActions"},!s&&n.a.createElement(n.a.Fragment,null,n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("Forward"),onClick:i},n.a.createElement("i",{className:"icon-forward"}))),t?n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("AccActionDownload"),onClick:v},u?n.a.createElement($.a,{progress:g,size:"s",onClick:v}):n.a.createElement("i",{className:"icon-download"})):n.a.createElement(B.a,{href:e,download:r,round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("AccActionDownload")},n.a.createElement("i",{className:"icon-download"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:a?"Zoom Out":"Zoom In",onClick:d},n.a.createElement("i",{className:a?"icon-zoom-out":"icon-zoom-in"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("Close"),onClick:l},n.a.createElement("i",{className:"icon-close"})))},V=a(9);a(244);var Y=({text:e="",isHideable:t,onClick:a})=>{const[c,r]=Object(n.r)(!1);return Object(n.n)(()=>{const e=document.querySelector(".MediaViewerFooter .media-text"),t=()=>{const t=e?e.clientHeight:0;r(t>2*i.c)};t();const a=Object(V.g)(t,500,!0);return window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[]),n.a.createElement("div",{className:"MediaViewerFooter "+(t?"hideable":""),onClick:function(t){e&&t.stopPropagation()}},e&&n.a.createElement("div",{className:"media-viewer-footer-content",onClick:a},n.a.createElement("p",{className:"media-text custom-scroll "+(c?"multiline":"")},e)))},W=a(29),K=a(123);const Q=function(){if(void 0!==document.fullscreenElement)return"fullscreenElement";if(void 0!==document.mozFullScreenElement)return"mozFullScreenElement";if(void 0!==document.webkitFullscreenElement)return"webkitFullscreenElement";return""}();var Z=a(137),X=a(134);const _=["bytes","kB","MB","GB","TB","PB"];var J=e=>{const t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**Math.floor(t)).toFixed(1)} ${_[t]}`};a(245);const ee=e=>{e.stopPropagation()};var te=({bufferedProgress:e,currentTime:t,duration:a,fileSize:c,isForceVisible:r,isForceMobileVersion:s,isPlayed:l,isFullscreenSupported:i,isFullscreen:d,onChangeFullscreen:m,onPlayPause:u,onSeek:h})=>{const[b,p]=Object(n.r)(!0);Object(n.n)(()=>{r&&p(r)},[r]),Object(n.n)(()=>{let e;return r||(o.f?p(!1):e=window.setTimeout(()=>{p(!1)},800)),()=>{e&&window.clearTimeout(e)}},[r]),Object(n.n)(()=>((b||r)&&document.body.classList.add("video-controls-visible"),()=>{document.body.classList.remove("video-controls-visible")}),[r,b]);const g=Object(F.a)();var v,E;if(b||r)return n.a.createElement("div",{className:"VideoPlayerControls "+(s?"mobile":""),onClick:ee},function(e,t,a,c){const r=e/t*100,s=100*a;return n.a.createElement("div",{className:"player-seekline"},n.a.createElement("div",{className:"player-seekline-track"},n.a.createElement("div",{className:"player-seekline-buffered",style:`width: ${s||0}%`}),n.a.createElement("div",{className:"player-seekline-played",style:`width: ${r||0}%`}),n.a.createElement("input",{min:"0",max:"100",step:.01,type:"range",onInput:c,className:"player-seekline-input",value:r||0})))}(t,a,e,h),n.a.createElement(B.a,{ariaLabel:g("AccActionPlay"),size:"tiny",ripple:!o.f,color:"translucent-white",className:"play",onClick:u},n.a.createElement("i",{className:l?"icon-pause":"icon-play"})),function(e,t){return n.a.createElement("div",{className:"player-time"},`${Object(D.e)(e)} / ${Object(D.e)(t)}`)}(t,a),e<1&&(v=e,E=c,n.a.createElement("div",{className:"player-file-size"},`${J(E*v)} / ${J(E)}`)),i&&n.a.createElement(B.a,{ariaLabel:"Fullscreen",size:"tiny",color:"translucent-white",className:"fullscreen",onClick:m},n.a.createElement("i",{className:""+(d?"icon-smallscreen":"icon-fullscreen")})))};a(246);function ae(){return(ae=Object.assign||function(e){for(var t=1;t{const m=Object(n.q)(null),[u,h]=Object(n.r)(!o.k||!o.d),[b,p]=Object(n.r)(0),[g,v]=Object(n.r)(!0),[E,f,O]=function(e,t){const[a,c]=Object(n.r)(Boolean(Q&&document[Q]));return Object(n.o)(()=>{const a=()=>{c(Boolean(Q&&document[Q]))},n=()=>{c(!0)},r=()=>{c(!1),t(!1)},s=e.current;return document.addEventListener("fullscreenchange",a,!1),document.addEventListener("webkitfullscreenchange",a,!1),document.addEventListener("mozfullscreenchange",a,!1),s&&(s.addEventListener("webkitbeginfullscreen",n,!1),s.addEventListener("webkitendfullscreen",r,!1)),()=>{document.removeEventListener("fullscreenchange",a,!1),document.removeEventListener("webkitfullscreenchange",a,!1),document.removeEventListener("mozfullscreenchange",a,!1),s&&(s.removeEventListener("webkitbeginfullscreen",n,!1),s.removeEventListener("webkitendfullscreen",r,!1))}},[]),Q||"iOS"===o.n?[a,()=>{e.current&&(Q||"iOS"===o.n)&&(e.current.requestFullscreen?e.current.requestFullscreen():e.current.webkitRequestFullscreen?e.current.webkitRequestFullscreen():e.current.webkitEnterFullscreen?e.current.webkitEnterFullscreen():e.current.mozRequestFullScreen&&e.current.mozRequestFullScreen(),c(!0))},()=>{e.current&&(document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),c(!1))}]:[!1]}(m,h),{isBuffered:j,bufferedProgress:C,bufferingHandlers:y}=Object(K.a)(),{shouldRender:k,transitionClassNames:N}=Object(W.a)(!j,void 0,void 0,"slow");Object(n.n)(()=>{i||!l?m.current.pause():e&&!o.k&&Object(X.a)(m.current)},[i,l,e]),Object(n.n)(()=>{m.current.currentTime===m.current.duration?(p(0),h(!1)):p(m.current.currentTime)},[b]);const I=Object(n.m)(e=>{e.stopPropagation(),u?(m.current.pause(),h(!1)):(m.current.play(),h(!0))},[u]);Object(Z.a)(m,[]);const S=Object(n.m)(()=>{v(!0)},[]),w=Object(n.m)(()=>{v(!1)},[]),P=Object(n.m)(e=>{p(e.currentTarget.currentTime)},[]),M=Object(n.m)(()=>{p(0),h(!1)},[]),F=Object(n.m)(()=>{E&&O?O():!E&&f&&f()},[O,E,f]),L=Object(n.m)(e=>{e.stopPropagation(),m.current.currentTime=Number(e.target.value)*m.current.duration/100},[]),A=Object(n.m)(e=>{e.stopPropagation(),v(!g)},[g]);Object(n.n)(()=>{const e=e=>{"Enter"!==e.key&&" "!==e.key||I(e)};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}},[I]);const T=c&&`width: ${c.width}px; height: ${c.height}px`,B=`background-image: url(${a})`;return n.a.createElement("div",{className:"VideoPlayer",onClick:!t&&o.f?A:void 0,onMouseOver:t?void 0:S,onMouseOut:t?void 0:w},n.a.createElement("div",{style:T},n.a.createElement("video",ae({ref:m,autoPlay:o.k,playsInline:!0,loop:t,muted:t,id:"media-viewer-video",style:B,onEnded:M},y,{onTimeUpdate:P}),e&&n.a.createElement("source",{src:e}))),k&&n.a.createElement("div",{className:["spinner-container",N].join(" ")},!j&&n.a.createElement("div",{className:"buffering"},"Buffering..."),n.a.createElement($.a,{size:"xl",progress:j?1:r,square:!0,onClick:d})),!t&&!k&&n.a.createElement(te,{isPlayed:u,bufferedProgress:C,currentTime:b,isFullscreenSupported:Boolean(f),isFullscreen:E,fileSize:s,duration:m.current?m.current.duration:0,isForceVisible:!u||g,isForceMobileVersion:c&&c.width<400,onSeek:L,onChangeFullscreen:F,onPlayPause:I}))}),ce=a(8);a(247);var re=Object(n.h)(({isShown:e,onChangeZoom:t})=>{const{transitionClassNames:a}=Object(W.a)(e),c=Object(O.a)(e),r=Object(n.q)(null),[s,l]=Object(n.r)(1),i=Object(n.q)(!1);Object(n.n)(()=>{e&&!c&&l(1.5)},[e,c]);const d=Object(n.m)(()=>{i.current=!0},[]),m=Object(n.m)(()=>{i.current=!1,1===s&&t(s,!i.current)},[t,s]);Object(n.n)(()=>{t(s,!i.current)},[s,t]);const u=Object(F.a)(),h=Object(ce.a)("ZoomControls",a);return n.a.createElement("div",{className:h},n.a.createElement(B.a,{disabled:1===s,size:"tiny",color:"translucent-white",ariaLabel:u("ZoomOut"),className:"zoom-out",ripple:!o.f,onClick:()=>{r.current&&l(Math.max(1,s-.5))}},n.a.createElement("i",{className:"icon-zoom-out"})),n.a.createElement(B.a,{disabled:3===s,size:"tiny",color:"translucent-white",ariaLabel:"Zoom In",className:"zoom-in",ripple:!o.f,onClick:()=>{r.current&&l(Math.min(3,s+.5))}},n.a.createElement("i",{className:"icon-zoom-in"})),n.a.createElement("div",{className:"seekline"},n.a.createElement("div",{className:"seekline-track"},n.a.createElement("div",{className:"seekline-played",style:`width: ${50*(s-1)}%`}),n.a.createElement("input",{ref:r,min:1,max:3,step:"0.5",value:s,type:"range",className:"seekline-input",onChange:e=>{l(Math.min(3,Math.max(Number(e.target.value),1)))},onMouseDown:d,onMouseUp:m}))))});a(248);const se=[1,0,0,1,0,0],le={1:1,1.5:1.5,2:2.2,2.5:3.3,3:5.5};var oe=Object(n.h)(({children:e,className:t,noWrap:a,canPan:c,zoomLevel:r,panDeltaX:s,panDeltaY:l,onPan:o})=>{const i=le[r]||r,[d,m]=Object(n.r)(!1),[h,b]=Object(n.r)({dx:s,dy:l,x:0,y:0}),[p,g]=Object(n.r)(se),v=Object(n.q)(null),E=Object(n.q)(null);Object(n.n)(()=>{const e=i||p[0],t=s||p[4],a=l||p[5],n=[...p];p[0]!==e&&(n[0]=e||n[0],n[3]=e||n[3]),p[4]!==t&&(n[4]=t),p[5]!==a&&(n[5]=a),Object(u.a)(p,n)||g(function(e,t,a){const n=a&&a.querySelector(".active img");if(!a||!n)return t;const c=a.getBoundingClientRect(),r=n.getBoundingClientRect(),s=r.width/e*t[0],l=r.height/e*t[3],o=(c.width-s)/2+t[4],i=(c.height-l)/2+t[5];return c.width&&c.width-150{c||g(se)},[c]),Object(n.n)(()=>{E.current&&(E.current.style.transform=`matrix(${p.toString()})`)},[a,p]);return a?e:n.a.createElement("div",{ref:v,className:"pan-wrapper "+(t||""),onMouseDown:e=>{if(!c)return;e.stopPropagation(),e.preventDefault();const t={dx:p[4],dy:p[5],x:e.pageX,y:e.pageY};b(t),m(!0),v.current&&v.current.classList.add("move")},onMouseUp:()=>{m(!1),v.current&&v.current.classList.remove("move"),o&&o(p[4],p[5])},onMouseMove:e=>{if(d){const t=function(e,t){const a=[...p],n=h.x-e,c=h.y-t;return a[4]=h.dx-n,a[5]=h.dy-c,a}(e.pageX,e.pageY);g(t),E.current&&(E.current.style.transform=`matrix(${p.toString()})`)}}},n.a.createElement("div",{ref:E,className:"pan-container"},e))});a(249);function ie(e,t){return e?n.a.createElement("img",{src:e,alt:"",style:t?`width: ${t.width}px`:"",draggable:!1}):n.a.createElement("div",{className:"spinner-wrapper",style:t?`width: ${t.width}px`:""},n.a.createElement(L.a,{color:"white"}))}var de=Object(n.h)(Object(c.h)(e=>{const{chatId:t,threadId:a,messageId:n,avatarOwnerId:c,profilePhotoIndex:r,origin:l}=e.mediaViewer,{animationLevel:o}=e.settings.byKey;if(l===s.h.SearchResult){if(!t||!n)return{animationLevel:o};const a=Object(d.k)(e,t,n);return a?{chatId:t,messageId:n,senderId:a.senderId,origin:l,message:a,animationLevel:o}:{animationLevel:o}}if(c){return{messageId:-1,senderId:c,avatarOwner:Object(d.Db)(e,c)||Object(d.f)(e,c),profilePhotoIndex:r||0,animationLevel:o,origin:l}}if(!(t&&a&&n))return{animationLevel:o};let i,m,u;if(i=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.mb)(e,t,n):Object(d.k)(e,t,n),!i)return{animationLevel:o};if(m=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.nb)(e,t):Object(d.m)(e,t),l===s.h.Inline||l===s.h.Album)u=Object(d.db)(e,t,a)||Object(d.X)(e,t,a);else if(l===s.h.SharedMedia){const t=Object(d.v)(e),{foundIds:a}=t&&t.resultsByType&&t.resultsByType.media||{};u=a}return{chatId:t,threadId:a,messageId:n,senderId:i.senderId,origin:l,message:i,chatMessages:m,collectionIds:u,animationLevel:o}},(e,t)=>Object(u.l)(t,["openMediaViewer","closeMediaViewer","openForwardMenu","focusMessage"]))(({chatId:e,threadId:t,messageId:a,senderId:c,origin:d,avatarOwner:u,profilePhotoIndex:y,message:I,chatMessages:S,collectionIds:w,openMediaViewer:P,closeMediaViewer:M,openForwardMenu:L,focusMessage:D,animationLevel:x})=>{const U=Object(n.q)(null),G=Boolean(u||a),z=I?Object(m.Q)(I):void 0,q=I?Object(m.G)(I):void 0,$=I?Object(m.O)(I):void 0,V=Boolean(z),W=Boolean(q||z),K=Boolean($),Q=$?$.isGif:void 0,Z=d===s.h.SharedMedia,X=d===s.h.SearchResult,_=x>=1?"mv-slide":"none",J=2===x?"slide-fade":"none",ee=2===x,te=u?`avatar${u.id}-${y}.jpg`:I&&Object(m.B)(I),ae=Object(O.a)(c),[ce,se]=Object(n.r)(!1),[le,de]=Object(n.r)(!1),[me,ue]=Object(n.r)(1),[he,be]=Object(n.r)({x:0,y:0}),pe=Object(n.p)(()=>V&&a?[a]:Object(m.i)(S||{},w||[],Z),[V,a,S,w,Z]),ge=a?pe.indexOf(a):-1,ve=0===ge||-1===ge,Ee=ge===pe.length-1||-1===ge;function fe(e){if(u&&void 0!==y){const{photos:t}=u;return t&&t[y]?`photo${t[y].id}?size=c`:Object(m.f)(u,e?"big":"normal")}return I&&Object(m.D)(I,e?"viewerFull":"viewerPreview")}!G||ae&&ae===c&&U.current||(U.current=ge);const Oe=Object(v.a)(I&&(Z||X)&&Object(m.D)(I,"pictogram"),void 0,r.ApiMediaFormat.BlobUrl,void 0,ee&&350),je=fe(),Ce=Object(v.a)(je,void 0,u&&je&&je.startsWith("profilePhoto")?r.ApiMediaFormat.DataUri:r.ApiMediaFormat.BlobUrl,void 0,ee&&350),{mediaData:ye,downloadProgress:ke}=Object(E.a)(fe(!0),void 0,I&&Object(m.C)(I,"viewerFull"),void 0,ee&&350),Ne=q||$?(q||$).blobUrl:void 0;let Ie=!K&&(Ne||ye)||Ce||Oe;const Se=Object(f.a)(!Ie&&I&&Object(m.E)(I));Ie||d===s.h.SearchResult||(Ie=Se);const we=W?Object(m.R)(V?Object(m.Q)(I):Object(m.G)(I)):void 0,Pe=K?Object(m.ab)(Object(m.O)(I)):void 0;Object(n.n)(()=>{o.f&&document.body.classList.toggle("is-media-viewer-open",G)},[G]);const Me=Object(g.a)();Object(n.n)(()=>{const e=window.matchMedia(i.b);return"function"==typeof e.addEventListener?e.addEventListener("change",Me):"function"==typeof e.addListener&&e.addListener(Me),()=>{"function"==typeof e.removeEventListener?e.removeEventListener("change",Me):"function"==typeof e.removeListener&&e.removeListener(Me)}},[Me]);const Fe=Object(O.a)(I),Le=Object(O.a)(d),Ae=Object(O.a)(u),Te=Object(O.a)(Ie);Object(n.n)(()=>{if(ee&&G&&!Fe&&!Ae){Object(j.b)(350+l.c);const e=I?Object(C.a)(I):void 0;k(Boolean(e),d,Ie,I)}ee&&!G&&(Fe||Ae)&&(Object(j.b)(350+l.c),N(Le,Te,Fe||void 0))},[ee,G,d,Le,I,Fe,Ae,Ie,Te]),Object(n.n)(()=>{let e;return le?se(!0):e=window.setTimeout(()=>{se(!1)},350),()=>{e&&window.clearTimeout(e)}},[le]);const Be=()=>{de(!1),ue(1),be({x:0,y:0})},De=Object(n.m)(()=>{de(!le),ue(le?1:1.5),le&&be({x:0,y:0})},[le]),xe=Object(n.m)((e,t=!1)=>{ue(e),1===e&&t&&Be()},[]),Ue=Object(n.m)(()=>{M(),Be()},[M]),Re=Object(n.m)(()=>{Ue(),D({chatId:e,threadId:t,messageId:a})},[Ue,e,t,D,a]),Ge=Object(n.m)(()=>{L({fromChatId:e,messageIds:[a]}),Be()},[L,e,a]);Object(n.n)(()=>G?Object(b.a)(()=>{le?Be():Ue()}):void 0,[Ue,G,le]),Object(n.n)(()=>{K&&!Q&&Object(p.b)()},[Q,K]);const ze=Object(n.m)((e,t)=>{let a=pe.indexOf(e);return(-1===t&&a>0||1===t&&a{ve||P({chatId:e,threadId:t,messageId:a?ze(a,-1):void 0,origin:d})},[e,t,ze,ve,a,P,d]),$e=Object(n.m)(()=>{Ee||P({chatId:e,threadId:t,messageId:a?ze(a,1):void 0,origin:d})},[e,t,ze,Ee,a,P,d]);Object(n.n)(()=>{const e=e=>{switch(e.key){case"Left":case"ArrowLeft":qe();break;case"Right":case"ArrowRight":$e()}};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}}),Object(n.n)(()=>{const e=document.querySelector(".slide-container > .active, .slide-container > .to");if(!e)return;const t=Q&&!o.d;return Object(h.b)(e,{excludedClosestSelector:".backdrop, .navigation, .media-viewer-head, .media-viewer-footer"+(t?"":", .VideoPlayer"),onClick:()=>{le||Ue()},onSwipe:o.k?(e,t)=>{t===h.a.Right?qe():t===h.a.Left?$e():Ue()}:void 0})},[Ue,Q,le,$e,qe,ce]);const He=Object(n.m)((e,t)=>{be({x:e,y:t})},[]),Ve=Object(F.a)();function Ye(t){if(u)return n.a.createElement("div",{key:e,className:"media-viewer-content"},ie(ye||Ce,Object(i.g)(i.a,!1)));if(I){const e=Object(C.a)(I),c=Boolean(e);return n.a.createElement("div",{key:a,className:"media-viewer-content "+(c?"has-footer":"")},W&&ie(Ne||ye||Ce||Oe,I&&Object(i.g)(we,c)),K&&n.a.createElement(ne,{key:a,url:Ne||ye,isGif:Q,posterData:Ie,posterSize:I&&Object(i.g)(Pe,c,!0),downloadProgress:ke,fileSize:$.size,isMediaViewerOpen:G,noPlay:!t,onClose:Ue}),e&&n.a.createElement(Y,{text:e,onClick:Re,isHideable:K}))}}function We(){return n.a.createElement(R,{key:u?u.id:a,chatId:u?u.id:e,messageId:a,isAvatar:Boolean(u)})}return n.a.createElement(A.a,{id:"MediaViewer",className:le?"zoomed":"",isOpen:G},()=>n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"media-viewer-head"},o.f&&n.a.createElement(B.a,{className:"media-viewer-close",round:!0,size:"smaller",color:"translucent-white",ariaLabel:Ve("Close"),onClick:Ue},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(T.a,{activeKey:U.current,name:J},We),n.a.createElement(H,{mediaData:ye||Ce,isVideo:K,isZoomed:le,message:I,fileName:te,onCloseMediaViewer:Ue,onForward:Ge,onZoomToggle:De,isAvatar:Boolean(u)})),n.a.createElement(oe,{noWrap:!ce,canPan:le,panDeltaX:he.x,panDeltaY:he.y,zoomLevel:me,onPan:He},n.a.createElement(T.a,{className:"slide-container",activeKey:ge,name:_},Ye)),!ve&&n.a.createElement("button",{type:"button",className:"navigation prev "+(K&&!Q&&"inline"),"aria-label":Ve("AccDescrPrevious"),onClick:qe}),!Ee&&n.a.createElement("button",{type:"button",className:"navigation next "+(K&&!Q&&"inline"),"aria-label":Ve("Next"),onClick:$e}),n.a.createElement(re,{isShown:le,onChangeZoom:xe})))})),me=a(46),ue=a(118),he=a(16),be=a(99),pe=a(40),ge=a(102),ve=a(95),Ee=a(98),fe=a(114);a(250);var Oe=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a},currentUserId:n}=e;return{chatsById:t,activeListIds:a.active,archivedListIds:a.archived,currentUserId:n}},(e,t)=>Object(u.l)(t,["setForwardChatId","exitForwardMode","loadMoreChats"]))(({chatsById:e,activeListIds:t,archivedListIds:a,currentUserId:c,isOpen:s,setForwardChatId:l,exitForwardMode:i,loadMoreChats:d})=>{const[u,h]=Object(n.r)(""),b=Object(n.q)(null);Object(n.n)(()=>{s?o.f||setTimeout(()=>{requestAnimationFrame(()=>{b.current&&b.current.focus()})},500):(b.current&&b.current.blur(),setTimeout(()=>{h("")},300))},[s]);const p=Object(n.p)(()=>{const n=[...t||[],...a||[]];return Object(m.Bb)([...n.filter(t=>{const a=e[t];return!a||!!Object(m.e)(a,r.MAIN_THREAD_ID)&&(!u||Object(me.a)(Object(m.l)(e[t],void 0,t===c),u))})],e,void 0,c?[c]:void 0)},[t,a,e,c,u]),[g,v]=Object(ue.a)(d,p,Boolean(u)),E=Object(n.m)(e=>{h(e.currentTarget.value)},[]),f=Object(F.a)(),O=n.a.createElement("div",{className:"modal-header"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:f("Close"),onClick:i},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(pe.a,{ref:b,value:u,onChange:E,placeholder:f("ForwardTo")}));return n.a.createElement(be.a,{isOpen:s,onClose:i,className:"ForwardPicker",header:O},g&&g.length?n.a.createElement(ge.a,{className:"picker-list custom-scroll",items:g,onLoadMore:v,noScrollRestore:Boolean(u)},g.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable force-rounded-corners",onClick:()=>l({id:e})},Object(m.kb)(e)?n.a.createElement(Ee.a,{status:e===c?f("SavedMessagesInfo"):void 0,userId:e}):n.a.createElement(fe.a,{chatId:e})))):g&&!g.length?n.a.createElement("p",{className:"no-results"},"Sorry, nothing found."):n.a.createElement(he.a,null))})),je=a(159);a(251);function Ce(e){return e.isSlowMode?"Slowmode enabled":"Something went wrong"}var ye=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["errors"]),(e,t)=>Object(u.l)(t,["dismissError"]))(({errors:e,dismissError:t})=>{const a=Object(F.a)();if(e.length)return n.a.createElement("div",{id:"Errors"},e.map(e=>n.a.createElement(be.a,{isOpen:!0,onClose:t,className:"error",title:Ce(e)},n.a.createElement("p",null,Object(je.a)(e)),n.a.createElement(B.a,{isText:!0,onClick:t},a("OK")))))})),ke=a(170);var Ne=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["notifications"]),(e,t)=>Object(u.l)(t,["dismissNotification"]))(({notifications:e,dismissNotification:t})=>{if(e.length)return n.a.createElement("div",{id:"Notifications"},e.map(({message:e})=>n.a.createElement(ke.a,{message:Object(x.a)(e,["emoji","br","links"]),onDismiss:t})))}));a(252);const Ie=["M","T","W","T","F","S","S"];function Se(e,t,a,n,c){const r=new Date(e,t,a,0,0,0,0),s=n&&new Date(n.getFullYear(),n.getMonth(),n.getDate(),0,0,0,0),l=c&&new Date(c.getFullYear(),c.getMonth(),c.getDate(),0,0,0,0);return!!(l&&r>l)||!!(s&&r{const h=new Date,b=Object(n.p)(()=>e?new Date(e):new Date,[e]),p=t?new Date(t):void 0,[g,v]=Object(n.r)(b),[E,f]=Object(n.r)(we(b.getHours())),[O,j]=Object(n.r)(we(b.getMinutes())),C=g.getFullYear(),y=g.getMonth(),k=g.getDate();Object(n.n)(()=>{r&&v(b)},[r,b]);const N=c&&C>=h.getFullYear()&&y>=h.getMonth()||p&&C>=p.getFullYear()&&y>=p.getMonth(),I=a&&C<=h.getFullYear()&&y<=h.getMonth(),S=Object(n.p)(()=>function(e,t){const a=[],n=new Date;n.setFullYear(e),n.setMonth(t),n.setDate(1);const c=n.getDay();for(let e=1;e{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return f(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),23)),n=new Date(g.getTime());n.setHours(a),v(n);const c=we(a);f(c),e.target.value=c},[g]),P=Object(n.m)(e=>{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return j(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),59)),n=new Date(g.getTime());n.setMinutes(a),v(n);const c=we(a);j(c),e.target.value=c},[g]);return n.a.createElement(be.a,{isOpen:r,onClose:d,className:"CalendarModal"},n.a.createElement("div",{className:"container"},n.a.createElement("div",{className:"month-selector"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h4",null,Object(D.f)(g,o.f)),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",disabled:I,onClick:I?void 0:function(){v(e=>{const t=new Date(e);return t.setMonth(t.getMonth()-1),t})}},n.a.createElement("i",{className:"icon-previous"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",disabled:N,onClick:N?void 0:function(){v(e=>{const t=new Date(e);return t.setMonth(t.getMonth()+1),t})}},n.a.createElement("i",{className:"icon-next"})))),n.a.createElement("div",{className:"calendar-wrapper"},n.a.createElement("div",{className:"calendar-grid"},Ie.map(e=>n.a.createElement("div",{className:"day-button faded weekday"},n.a.createElement("span",null,e))),S.map(e=>n.a.createElement("div",{role:"button",tabIndex:0,onClick:()=>{return t=e,void v(e=>{const a=new Date(e);return a.setDate(t),a});var t},className:Object(ce.a)("day-button",Se(C,y,e,a?h:void 0,c?h:p)?"disabled":""+(e?"clickable":""),e===k&&"selected")},!!e&&n.a.createElement("span",null,e))))),s&&n.a.createElement("div",{className:"timepicker"},n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:E,onChange:w}),":",n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:O,onChange:P})),n.a.createElement("div",{className:"footer"},n.a.createElement(B.a,{onClick:function(){m(g)}},s?function(e){const t=Object(D.c)(e,!0);return`Send ${"Today"===t?t:"on "+t} at ${Object(D.h)(e)}`}(g):l),i&&n.a.createElement(B.a,{onClick:u,isText:!0},i)))});var Me=Object(n.h)(Object(c.h)((e,{message:t,isSchedule:a})=>{const{threadId:n}=Object(d.y)(e)||{},{canDeleteForAll:c}=n&&Object(d.b)(e,t,n)||{},r=Object(d.f)(e,t.chatId);return{canDeleteForAll:!a&&c,contactName:r&&Object(m.kb)(r.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(r))):void 0,willDeleteForCurrentUserOnly:r&&Object(m.hb)(r)&&!c,willDeleteForAll:r&&Object(m.mb)(r)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages"]))(({isOpen:e,isSchedule:t,message:a,album:c,canDeleteForAll:r,contactName:s,willDeleteForCurrentUserOnly:l,willDeleteForAll:o,onClose:i,deleteMessages:d,deleteScheduledMessages:m})=>{const u=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];d({messageIds:e,shouldDeleteForAll:!0}),i()},[d,a.id,i,c]),h=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];t?m({messageIds:e}):d({messageIds:e,shouldDeleteForAll:!1}),i()},[c,a.id,t,i,m,d]),b=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:i,onEnter:e&&!r?h:void 0,className:"delete",title:b("DeleteSingleMessagesTitle")},n.a.createElement("p",null,b("AreYouSureDeleteSingleMessage")),l&&n.a.createElement("p",null,"This will delete it just for you, not for other participants in the chat."),o&&n.a.createElement("p",null,"This will delete it for everyone in this chat."),r&&n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},"Delete for ",s?"me and ":"Everyone",s&&Object(x.a)(s)),n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},"Delete",r?" just for me":""),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:i},b("Cancel")))}));var Fe=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(m.kb)(t),n=Object(d.O)(e,t),c=Object(d.f)(e,t),r=!!c&&Object(m.ib)(c),s=!!c&&Object(m.hb)(c),l=!!c&&Object(m.mb)(c);return{isPrivateChat:a,isChatWithSelf:n,isChannel:r,isGroup:s,isSuperGroup:l,canPinForAll:a&&!n||l||s,contactName:c&&Object(m.kb)(c.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(c))):void 0}},(e,t)=>Object(u.l)(t,["pinMessage"]))(({isOpen:e,messageId:t,chatId:a,isChannel:c,isGroup:r,isSuperGroup:s,canPinForAll:l,contactName:o,onClose:i,pinMessage:d})=>{const m=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1}),i()},[d,a,t,i]),u=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1,isOneSide:!0,isSilent:!0}),i()},[a,t,i,d]),h=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:i,className:"pin",header:n.a.createElement("div",{className:"modal-header"},n.a.createElement("h3",{className:"modal-title"},h("PinMessageAlertTitle")))},c?n.a.createElement("p",null,h("PinMessageAlertChannel")):r||s?n.a.createElement("p",null,h("PinMessageAlert")):n.a.createElement("p",null,h("PinMessageAlertChat")),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:u},h("DialogPin")),l&&n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:m},o?"Pin for me and "+o:"Pin and notify all memebers"),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:i},h("Cancel")))}));var Le=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=t?Object(d.gb)(e,t):[];return{pinnedMessagesCount:a?a.length:0}})(({isOpen:e,pinnedMessagesCount:t,onClose:a,onUnpin:c})=>{const r=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:a,className:"unpin-all",header:n.a.createElement("div",{className:"modal-header"},n.a.createElement("h3",{className:"modal-title"},r("UnpinAllMessages")))},n.a.createElement("p",null,"Do you want to unpin all ",t," messages in this chat?"),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:c},r("DialogUnpin")),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:a},r("Cancel")))})),Ae=a(28),Te=a(50);var Be=Object(n.h)(Object(c.h)((e,{isSchedule:t})=>{const{messageIds:a}=e.selectedMessages||{},{canDeleteForAll:n}=Object(d.e)(e),c=Object(d.r)(e);return{selectedMessageIds:a,canDeleteForAll:!t&&n,contactName:c&&Object(m.kb)(c.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(c))):void 0,willDeleteForCurrentUserOnly:c&&Object(m.hb)(c)&&!n,willDeleteForAll:c&&Object(m.mb)(c)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages","exitMessageSelectMode"]))(({isOpen:e,isSchedule:t,selectedMessageIds:a,canDeleteForAll:c,contactName:r,willDeleteForCurrentUserOnly:s,willDeleteForAll:l,onClose:o,deleteMessages:i,deleteScheduledMessages:d,exitMessageSelectMode:m})=>{const u=Object(n.m)(()=>{i({messageIds:a,shouldDeleteForAll:!0}),m(),o()},[i,m,a,o]),h=Object(n.m)(()=>{t?d({messageIds:a}):i({messageIds:a,shouldDeleteForAll:!1}),m(),o()},[t,m,o,d,a,i]),b=Object(F.a)();if(a)return n.a.createElement(be.a,{isOpen:e,onClose:o,onEnter:c?void 0:h,className:"delete",title:"Delete Messages?"},n.a.createElement("p",null,b("AreYouSureDeleteFewMessages")),s&&n.a.createElement("p",null,"This will delete them just for you, not for other participants in the chat."),l&&n.a.createElement("p",null,"This will delete them for everyone in this chat."),c&&n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},"Delete for ",r?"me and ":"Everyone",r&&Object(x.a)(r)),n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},"Delete",c?" just for me":""),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:o},b("Cancel")))}));a(253);var De=Object(n.h)(Object(c.h)(e=>{const{type:t}=Object(d.y)(e)||{},{canDelete:a}=Object(d.e)(e);return{isSchedule:"scheduled"===t,selectedMessagesCount:Object(d.pb)(e),canDeleteMessages:a}},(e,t)=>Object(u.l)(t,["exitMessageSelectMode","openForwardMenuForSelectedMessages"]))(({canPost:e,isActive:t,messageListType:a,isSchedule:c,selectedMessagesCount:r,canDeleteMessages:s,exitMessageSelectMode:l,openForwardMenuForSelectedMessages:o})=>{const[i,d,m]=Object(Ae.a)();Object(n.n)(()=>t&&!i?Object(Te.a)({onBackspace:d,onDelete:d,onEsc:l}):void 0,[t,i,d,l]);const u=Object(O.a)(r||void 0,!0),h=t?r:u,b=Object(F.a)(),p=b("VoiceOver.Chat.MessagesSelected",h),g=Object(ce.a)("MessageSelectToolbar",e&&"with-composer",t&&"shown");return n.a.createElement("div",{className:g},n.a.createElement("div",{className:"MessageSelectToolbar-inner"},n.a.createElement(B.a,{color:"translucent",round:!0,onClick:l,ariaLabel:"Exit select mode"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("span",{className:"MessageSelectToolbar-count",title:p},p),!!r&&n.a.createElement("div",{className:"MessageSelectToolbar-actions"},"scheduled"!==a&&n.a.createElement(q.a,{icon:"forward",ariaLabel:"Forward Messages",onClick:o},n.a.createElement("span",{className:"item-text"},b("Forward"))),n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:d,disabled:!s,ariaLabel:b("EditAdminGroupDeleteMessages")},n.a.createElement("span",{className:"item-text"},b("Delete"))))),n.a.createElement(Be,{isOpen:i,isSchedule:c,onClose:m}))})),xe=a(158),Ue=a(45),Re=a(160),Ge=a(149);var ze=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(m.T)(a);return{chat:a,privateChatUser:n?Object(d.Db)(e,n):void 0,isPinned:Object(d.M)(e,t)}})(({chatId:e,chat:t,privateChatUser:a,isPinned:c,withUsername:r,onClick:s})=>{const[l,o,i]=Object(Ae.a)(),d=Object(Re.a)({chat:t,privateChatUser:a,isPinned:c,handleDelete:o});if(t)return n.a.createElement(ve.a,{className:"chat-item-clickable search-result",onClick:()=>s(e),contextActions:d},Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e,withUsername:r,avatarSize:"large"}):n.a.createElement(fe.a,{chatId:e,withUsername:r,avatarSize:"large"}),n.a.createElement(Ge.a,{isOpen:l,onClose:i,chat:t}))})),qe=a(130);a(254);const $e=Object(V.g)(e=>e(),6e4,!0);var He=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.topPeers,a=e.users.byId,{recentlyFoundChatIds:n}=e.globalSearch;return{topUserIds:t,usersById:a,recentlyFoundChatIds:n}},(e,t)=>Object(u.l)(t,["loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats"]))(({topUserIds:e,usersById:t,recentlyFoundChatIds:a,onReset:c,loadTopUsers:r,loadContactList:s,openChat:l,addRecentlyFoundChatId:o,clearRecentlyFoundChats:i})=>{const d=Object(n.q)(null);Object(n.n)(()=>{$e(()=>{r(),s()})},[r,s]),Object(qe.a)(d,!e);const u=Object(n.m)(e=>{l({id:e}),c(),setTimeout(()=>{o({id:e})},250)},[l,o,c]),h=Object(F.a)();return n.a.createElement("div",{className:"RecentContacts custom-scroll"},e&&n.a.createElement("div",{className:"top-peers-section"},n.a.createElement("div",{ref:d,className:"top-peers no-selection"},e.map(e=>n.a.createElement("div",{className:"top-peer-item",onClick:()=>u(e)},n.a.createElement(U.a,{user:t[e]}),n.a.createElement("div",{className:"top-peer-name"},Object(x.a)(Object(m.X)(t[e])||" ")))))),a&&n.a.createElement("div",{className:"search-section pt-1"},n.a.createElement("h3",{className:"section-heading mt-0 recent-chats-header"},h("Recent"),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:"Clear recent chats",onClick:i},n.a.createElement("i",{className:"icon-close"}))),a.map(e=>n.a.createElement(ze,{chatId:e,onClick:u}))))})),Ve=a(122),Ye=a(110);a(255);var We=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);if(!a)return{};const n=Object(m.T)(a);return{chat:a,...n&&{privateChatUser:Object(d.Db)(e,n)},lastSyncTime:e.lastSyncTime}},(e,t)=>Object(u.l)(t,["focusMessage"]))(({message:e,searchQuery:t,chatId:a,chat:c,privateChatUser:r,focusMessage:s,lastSyncTime:l})=>{const i=Object(m.E)(e),d=Object(v.a)(Object(m.D)(e,"micro")),u=Object(n.m)(()=>{s({chatId:a,messageId:e.id})},[a,s,e.id]);if(Object(F.a)(),c)return n.a.createElement(ve.a,{className:"ChatMessage chat-item-clickable",ripple:!o.f,onClick:u},n.a.createElement(U.a,{chat:c,user:r,withOnlineStatus:!0,isSavedMessages:r&&r.isSelf,lastSyncTime:l}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"info-row"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",null,Object(x.a)(Object(m.l)(c,r))),c.isVerified&&n.a.createElement(Ve.a,null)),n.a.createElement("div",{className:"message-date"},n.a.createElement(Ye.a,{className:"date"},Object(D.g)(1e3*e.date)))),n.a.createElement("div",{className:"subtitle"},n.a.createElement("div",{className:"message"},function(e,t,a){if(!t)return Object(x.a)(Object(m.M)(e));return n.a.createElement("span",{className:"media-preview"},n.a.createElement("img",{src:t,alt:""}),Object(m.O)(e)&&n.a.createElement("i",{className:"icon-play"}),Object(x.a)(Object(m.M)(e,!0),["emoji","highlight"],{highlight:a}))}(e,d||i,t)))))}));a(256);var Ke=Object(n.h)(({searchDate:e,onSelect:t})=>{const a=Object(n.p)(()=>function(e){if(e.match(/^\d{2,4}-\d{2}-\d{2}$/g)){const t=new Date(e);return[{date:t,text:Object(D.a)(t)}]}const t=[],a=new Date,n=a.getFullYear(),c=a.getTime()>new Date(`${n}-${e}`).getTime()?n:n-1;for(let a=0;a<8;a++){const n=new Date(`${c-a}-${e}`);t.push({date:n,text:Object(D.a)(n)})}return t}(e),[e]);return n.a.createElement("section",{className:"DateSuggest custom-scroll custom-scroll-x"},a.map(({date:e,text:a})=>n.a.createElement("div",{onClick:()=>t(e),className:"date-item",key:a},n.a.createElement("i",{className:"icon-calendar"}),n.a.createElement("span",null,a))))}),Qe=a(108),Ze=a(129),Xe=a(11);const _e=Object(V.g)(e=>e(),500,!0);var Je=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{byId:a}=e.users,{userIds:n}=e.contactList||{};if(!n)return{chatsById:t,usersById:a};const{currentUserId:c,messages:r,lastSyncTime:s}=e,{fetchingStatus:l,globalResults:o,localResults:i,resultsByType:d}=e.globalSearch,{chatIds:m,userIds:u}=o||{},{chatIds:h,userIds:b}=i||{},{byChatId:p}=r,{foundIds:g}=d&&d.text||{};return{currentUserId:c,localContactIds:n,localChatIds:h,localUserIds:b,globalChatIds:m,globalUserIds:u,foundIds:g,globalMessagesByChatId:p,chatsById:t,usersById:a,fetchingStatus:l,lastSyncTime:s}},(e,t)=>Object(u.l)(t,["openChat","addRecentlyFoundChatId","searchMessagesGlobal","setGlobalSearchChatId"]))(({searchQuery:e,searchDate:t,dateSearchQuery:a,currentUserId:c,localContactIds:r,localChatIds:l,localUserIds:i,globalChatIds:d,globalUserIds:h,foundIds:b,globalMessagesByChatId:p,chatsById:g,usersById:v,fetchingStatus:E,lastSyncTime:f,onReset:O,onSearchDateSelect:j,openChat:C,addRecentlyFoundChatId:y,searchMessagesGlobal:k,setGlobalSearchChatId:N})=>{const[I,S]=Object(n.r)(!1),[w,P]=Object(n.r)(!1),M=Object(n.m)(({direction:t})=>{f&&t===s.e.Backwards&&_e(()=>{k({type:"text",query:e})})},[f,k,e]),L=Object(n.m)(e=>{C({id:e}),e!==c&&y({id:e}),o.f||O()},[c,C,y,O]),A=Object(n.m)(e=>{N({id:e})},[N]),T=Object(n.p)(()=>{if(!e||e.startsWith("@")&&e.length<2)return Ue.a;const t=r?r.filter(t=>{const a=v[t];if(!a)return!1;const n=Object(m.Y)(a);return n&&Object(me.a)(n,e)||Object(me.a)(a.username,e)}):[];return[...c&&Object(me.a)(Object(Xe.b)("SavedMessages"),e)?[c]:[],...Object(m.Bb)(Object(u.o)([...t,...l||[],...i||[]]),g)]},[e,r,c,l,i,g,v]),B=Object(n.p)(()=>!e||e.length<4||!d||!h?Ue.a:Object(m.Bb)(Object(u.o)([...d,...h]),g,!0),[g,d,h,e]),D=Object(n.p)(()=>(e||t)&&b&&0!==b.length?b.map(e=>{const[t,a]=e.split("_").map(Number);return p&&p[t]&&p[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):Ue.a,[b,p,e,t]),x=Object(n.m)(()=>{S(!I)},[I]),U=Object(n.m)(()=>{P(!w)},[w]),R=Object(F.a)();const G=E&&!E.chats&&!E.messages&&!T.length&&!B.length&&!D.length;return e||t?n.a.createElement(ge.a,{className:"LeftSearch custom-scroll",items:D,onLoadMore:M,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Ke,{searchDate:a,onSelect:j})),G&&n.a.createElement(Qe.a,null),!!T.length&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},T.map(e=>n.a.createElement(Ze.a,{chatOrUserId:e,onClick:A,clickArg:e}))),!!T.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},T.length>3&&n.a.createElement(Ye.a,{onClick:x},I?"Show less":"Show more"),"Contacts and Chats"),T.map((e,t)=>{if(I||!(t>=3))return n.a.createElement(ze,{chatId:e,onClick:L})})),!!B.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},B.length>3&&n.a.createElement(Ye.a,{onClick:U},w?"Show less":"Show more"),"Global Search"),B.map((e,t)=>{if(w||!(t>=3))return n.a.createElement(ze,{chatId:e,withUsername:!0,onClick:L})})),!!D.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},R("SearchMessages")),D.map((function(t){const a=Object(m.M)(t),c=g[t.chatId];if(a&&c)return n.a.createElement(We,{chatId:t.chatId,message:t,searchQuery:e})})))):n.a.createElement(He,{onReset:O})}));const et=Object(V.g)(e=>e(),500,!0);var tt=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{currentUserId:a,messages:{byChatId:n},lastSyncTime:c}=e,{fetchingStatus:r,resultsByType:s}=e.globalSearch,{foundIds:l}=s&&s.text||{};return{currentUserId:a,foundIds:l,globalMessagesByChatId:n,chatsById:t,fetchingStatus:r,lastSyncTime:c}},(e,t)=>Object(u.l)(t,["searchMessagesGlobal"]))(({searchQuery:e,currentUserId:t,dateSearchQuery:a,foundIds:c,globalMessagesByChatId:r,chatsById:l,fetchingStatus:o,lastSyncTime:i,searchMessagesGlobal:d,onSearchDateSelect:u})=>{const h=Object(n.m)(({direction:a})=>{i&&a===s.e.Backwards&&et(()=>{d({type:"text",query:e,chatId:t})})},[t,i,d,e]),b=Object(n.p)(()=>c&&0!==c.length?c.map(e=>{const[t,a]=e.split("_").map(Number);return r&&r[t]&&r[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):Ue.a,[c,r]);const p=o&&!o.chats&&!o.messages&&!b.length;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content custom-scroll chat-list",items:b,onLoadMore:h,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Ke,{searchDate:a,onSelect:u})),p&&n.a.createElement(Qe.a,null),!!b.length&&b.map((function(t){const a=Object(m.M)(t),c=l[t.chatId];if(a&&c)return n.a.createElement(We,{chatId:t.chatId,message:t,searchQuery:e})}))))}));function at(e){return(t,a)=>{const{byId:n}=t.chats,{byId:c}=t.users,{fetchingStatus:r,resultsByType:s,chatId:l}=t.globalSearch,o="audio"!==e?e:a&&a.isVoice?"voice":"audio",{byChatId:i}=t.messages,{foundIds:d}=s&&s[o]||{};return{isLoading:void 0===d||!!r&&Boolean(r.chats||r.messages),chatsById:n,usersById:c,globalMessagesByChatId:i,foundIds:d,searchChatId:l,lastSyncTime:t.lastSyncTime}}}var nt=a(155),ct=a(109);const rt=Object(V.g)(e=>e(),500,!0);var st=Object(n.h)(Object(c.h)(at("media"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","openMediaViewer"]))(({searchQuery:e,searchChatId:t,isLoading:a,globalMessagesByChatId:c,foundIds:r,lastSyncTime:o,searchMessagesGlobal:i,openMediaViewer:d})=>{const m=Object(n.m)(({direction:a})=>{o&&a===s.e.Backwards&&rt(()=>{i({type:"media",query:e,chatId:t})})},[o,i,e,t]),u=Object(n.p)(()=>r&&c?r.map(e=>{const[t,a]=e.split("_").map(Number);return c[t]&&c[t].byId[a]}).filter(Boolean):Ue.a,[c,r]),h=Object(n.m)((e,t)=>{d({chatId:t,messageId:e,origin:s.h.SearchResult})},[d]);const b=Object(ct.a)([e],l.nb)&&!a,p=b&&r&&r.length>0&&!e,g=b&&r&&r.length>0&&e,v=Object(ce.a)("search-content custom-scroll",g&&"chat-list");return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:v,items:u,itemSelector:e?".ListItem":".Media",onLoadMore:m,noFastList:!0},!b&&n.a.createElement(he.a,null),b&&(!r||0===r.length)&&n.a.createElement(Qe.a,null),p&&n.a.createElement("div",{className:"media-list"},u.map(e=>n.a.createElement(nt.a,{key:e.id,idPrefix:"search-media",message:e,onClick:h}))),g&&u.map(e=>n.a.createElement(We,{key:e.id,chatId:e.chatId,message:e}))))}));function lt(e,t,a){const{senderId:n}=e;if(!n)return;const c=Object(m.kb)(n)?a[n]:t[n];let r=Object(m.U)(c);const s=t[e.chatId];return s&&(Object(m.kb)(n)&&c.isSelf?r="You → "+Object(m.l)(s):Object(m.jb)(s)&&(r+=" → "+Object(m.l)(s))),r}var ot=a(174);const it=Object(V.g)(e=>e(),500,!0);var dt=Object(n.h)(Object(c.h)(at("links"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:m,focusMessage:u})=>{const h=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&it(()=>{m({type:"links",query:e,chatId:t})})},[d,m,e,t]),b=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number);return o[t]&&o[t].byId[a]}).filter(Boolean):Ue.a,[o,i]),p=Object(n.m)((e,t)=>{u({chatId:t,messageId:e})},[u]);const g=Object(ct.a)([e],l.nb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:b,onLoadMore:h,noFastList:!0},!g&&n.a.createElement(he.a,null),g&&(!i||0===i.length)&&n.a.createElement(Qe.a,null),g&&i&&i.length>0&&b.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(b[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(ot.a,{key:e.id,message:e,senderTitle:lt(e,c,r),onMessageClick:p}))})))})),mt=a(152);const ut=Object(V.g)(e=>e(),500,!0);var ht=Object(n.h)(Object(c.h)(at("documents"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:u,focusMessage:h})=>{const b=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&ut(()=>{u({type:"documents",query:e,chatId:t})})},[d,u,e,t]),p=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number),n=o[t]&&o[t].byId[a];return n&&Object(m.y)(n)?n:void 0}).filter(Boolean):Ue.a,[o,i]),g=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]);const v=Object(ct.a)([e],l.nb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:p,onLoadMore:b,noFastList:!0},!v&&n.a.createElement(he.a,null),v&&(!i||0===i.length)&&n.a.createElement(Qe.a,null),v&&i&&i.length>0&&p.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(p[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(mt.a,{message:e,withDate:!0,datetime:e.date,smaller:!0,sender:lt(e,c,r),className:"scroll-item",onDateClick:g}))})))})),bt=a(157);const pt=Object(V.g)(e=>e(),500,!0);var gt=Object(n.h)(Object(c.h)(at("audio"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage","openAudioPlayer"]))(({isVoice:e,searchQuery:t,searchChatId:a,isLoading:c,chatsById:r,usersById:o,globalMessagesByChatId:i,foundIds:d,lastSyncTime:m,searchMessagesGlobal:u,focusMessage:h,openAudioPlayer:b})=>{const p=e?"voice":"audio",g=Object(n.m)(({direction:e})=>{m&&e===s.e.Backwards&&pt(()=>{u({type:p,query:t,chatId:a})})},[p,m,u,t,a]),v=Object(n.p)(()=>d&&i?d.map(e=>{const[t,a]=e.split("_").map(Number);return i[t]&&i[t].byId[a]}).filter(Boolean):Ue.a,[i,d]),E=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]),f=Object(n.m)((e,t)=>{b({chatId:t,messageId:e})},[b]);const O=Object(ct.a)([t],l.nb)&&!c;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:v,onLoadMore:g,noFastList:!0},!O&&n.a.createElement(he.a,null),O&&(!d||0===d.length)&&n.a.createElement(Qe.a,null),O&&d&&d.length>0&&v.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(v[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(bt.a,{key:e.id,message:e,renderingFor:"searchResult",senderTitle:lt(e,r,o),date:e.date,lastSyncTime:m,className:"scroll-item",onPlay:f,onDateClick:E}))})))}));a(257);const vt=[{type:s.c.ChatList,title:"SearchAllChatsShort"},{type:s.c.Media,title:"SharedMediaTab2"},{type:s.c.Links,title:"SharedLinksTab2"},{type:s.c.Files,title:"SharedFilesTab2"},{type:s.c.Music,title:"SharedMusicTab2"},{type:s.c.Voice,title:"SharedVoiceTab2"}],Et=[{type:s.c.ChatList,title:"All Messages"},...vt.slice(1)],ft=Object.keys(s.c).length/2;var Ot=Object(n.h)(Object(c.h)(e=>{const{currentContent:t,chatId:a}=e.globalSearch;return{currentContent:t,chatId:a}},(e,t)=>Object(u.l)(t,["setGlobalSearchContent","setGlobalSearchDate"]))(({searchQuery:e,searchDate:t,currentContent:a=s.c.ChatList,chatId:c,setGlobalSearchContent:r,setGlobalSearchDate:l,onReset:o})=>{const[i,d]=Object(n.r)(0),m=Object(n.p)(()=>Object(D.l)(e),[e]),u=Object(n.m)(e=>{const t=vt[e];r({content:t.type}),d(e)},[r]),h=Object(n.m)(e=>{l({date:e.getTime()/1e3})},[l]);return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(xe.a,{activeTab:i,tabs:c?Et:vt,onSwitchTab:u}),n.a.createElement(T.a,{name:"slide",renderCount:ft,activeKey:a},()=>{switch(a){case s.c.ChatList:return c?n.a.createElement(tt,{searchQuery:e,dateSearchQuery:m,onReset:o,onSearchDateSelect:h}):n.a.createElement(Je,{searchQuery:e,searchDate:t,dateSearchQuery:m,onReset:o,onSearchDateSelect:h});case s.c.Media:return n.a.createElement(st,{searchQuery:e});case s.c.Links:return n.a.createElement(dt,{searchQuery:e});case s.c.Files:return n.a.createElement(ht,{searchQuery:e});case s.c.Music:return n.a.createElement(gt,{key:"audio",searchQuery:e});case s.c.Voice:return n.a.createElement(gt,{key:"voice",isVoice:!0,searchQuery:e});default:return}}))}));function jt(e,t){const a=Object(n.q)(e),[c,r]=Object(n.r)(t);return[c,Object(n.m)(e=>{r(t=>a.current(t,e))},[])]}const Ct=[{icon:"user",title:"FilterContacts",key:"contacts"},{icon:"non-contacts",title:"FilterNonContacts",key:"nonContacts"},{icon:"group",title:"FilterGroups",key:"groups"},{icon:"channel",title:"FilterChannels",key:"channels"},{icon:"bots",title:"FilterBots",key:"bots"}],yt=[{icon:"mute",title:"FilterMuted",key:"excludeMuted"},{icon:"archive",title:"FilterArchived",key:"excludeArchived"},{icon:"readchats",title:"FilterRead",key:"excludeRead"}],kt=["includedChatIds","bots","channels","groups","contacts","nonContacts"],Nt=["excludedChatIds","excludeArchived","excludeMuted","excludeRead"];function It(e,t,a){let n=[],c=[];if("included"===t){const{includedChatIds:t,...r}=a?e.includeFilters||{}:Object(u.l)(e.folder,kt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}else{const{excludedChatIds:t,...r}=a?e.excludeFilters||{}:Object(u.l)(e.folder,Nt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}return{selectedChatIds:n,selectedChatTypes:c}}function St(e){if(e){const{includedChatIds:t,...a}=e;if(Object.values(a).filter(Boolean).length>1||t&&t.length)return"";if(a.bots)return"Bots";if(a.groups)return"Groups";if(a.channels)return"Channels";if(a.contacts)return"Contacts";if(a.nonContacts)return"Non-Contacts"}return""}const wt={mode:"create",chatFilter:"",folder:{title:"",includedChatIds:[],excludedChatIds:[]}},Pt=(e,t)=>{switch(t.type){case"setTitle":return{...e,folder:{...e.folder,title:t.payload},isTouched:!0};case"editIncludeFilters":return{...e,includeFilters:Object(u.l)(e.folder,kt)};case"editExcludeFilters":return{...e,excludeFilters:Object(u.l)(e.folder,Nt)};case"setIncludeFilters":return{...e,includeFilters:t.payload,chatFilter:""};case"setExcludeFilters":return{...e,excludeFilters:t.payload,chatFilter:""};case"saveFilters":return e.includeFilters?{...e,folder:{...Object(u.j)(e.folder,kt),title:e.folder.title?e.folder.title:St(e.includeFilters),...e.includeFilters},includeFilters:void 0,chatFilter:"",isTouched:!0}:e.excludeFilters?{...e,folder:{...Object(u.j)(e.folder,Nt),...e.excludeFilters},excludeFilters:void 0,chatFilter:"",isTouched:!0}:e;case"editFolder":{const{id:e,description:a,...n}=t.payload;return{mode:"edit",folderId:e,folder:n,chatFilter:""}}case"setChatFilter":return{...e,chatFilter:t.payload};case"setIsLoading":return{...e,isLoading:t.payload};case"setError":return{...e,error:t.payload};case"reset":return wt;default:return e}};const Mt={currentPassword:"",password:"",hint:"",email:""},Ft=(e,t)=>{switch(t.type){case"setCurrentPassword":return{...e,currentPassword:t.payload};case"setPassword":return{...e,password:t.payload};case"setHint":return{...e,hint:t.payload};case"setEmail":return{...e,email:t.payload};case"reset":return Mt;default:return e}};var Lt=a(107);var At=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["signOut","deleteChatFolder"]))(({currentScreen:e,editedFolderId:t,onReset:a,onSaveFilter:c,signOut:r,deleteChatFolder:l})=>{const[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(n.m)(()=>{d(!0)},[]),b=Object(n.m)(()=>{d(!1)},[]),p=Object(n.m)(()=>{u(!0)},[]),g=Object(n.m)(()=>{u(!1)},[]),v=Object(n.m)(()=>{b(),r()},[b,r]),E=Object(n.m)(()=>{g(),l({id:t}),a()},[t,g,l,a]),f=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(B.a,{round:!0,ripple:!o.f,size:"smaller",color:"translucent",className:t?"active":"",onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]),O=Object(F.a)();return n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:a,ariaLabel:O("AccDescrGoBack")},n.a.createElement("i",{className:"icon-arrow-left"})),function(){switch(e){case s.m.EditProfile:return n.a.createElement("h3",null,O("EditProfile"));case s.m.General:return n.a.createElement("h3",null,O("General"));case s.m.Notifications:return n.a.createElement("h3",null,O("Notifications"));case s.m.Privacy:return n.a.createElement("h3",null,O("PrivacySettings"));case s.m.Language:return n.a.createElement("h3",null,O("Language"));case s.m.GeneralChatBackground:return n.a.createElement("h3",null,O("ChatBackground"));case s.m.GeneralChatBackgroundColor:return n.a.createElement("h3",null,O("SetColor"));case s.m.PrivacyPhoneNumber:return n.a.createElement("h3",null,O("PrivacyPhone"));case s.m.PrivacyLastSeen:return n.a.createElement("h3",null,O("PrivacyLastSeen"));case s.m.PrivacyProfilePhoto:return n.a.createElement("h3",null,O("Privacy.ProfilePhoto"));case s.m.PrivacyForwarding:return n.a.createElement("h3",null,O("PrivacyForwards"));case s.m.PrivacyGroupChats:return n.a.createElement("h3",null,O("AutodownloadGroupChats"));case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement("h3",null,O("AlwaysShareWith"));case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement("h3",null,O("NeverShareWith"));case s.m.PrivacyActiveSessions:return n.a.createElement("h3",null,O("SessionsTitle"));case s.m.PrivacyBlockedUsers:return n.a.createElement("h3",null,O("BlockedUsers"));case s.m.TwoFaDisabled:case s.m.TwoFaEnabled:return n.a.createElement("h3",null,O("TwoStepVerification"));case s.m.TwoFaNewPassword:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:return n.a.createElement("h3",null,O("EnterPassword"));case s.m.TwoFaNewPasswordConfirm:return n.a.createElement("h3",null,O("PleaseReEnterPassword"));case s.m.TwoFaNewPasswordHint:case s.m.TwoFaChangePasswordHint:return n.a.createElement("h3",null,O("PasswordHint"));case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaRecoveryEmail:return n.a.createElement("h3",null,O("RecoveryEmailTitle"));case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement("h3",null,"Recovery Email Code");case s.m.TwoFaCongratulations:return n.a.createElement("h3",null,O("TwoStepVerificationPasswordSet"));case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement("h3",null,O("PleaseEnterCurrentPassword"));case s.m.Folders:return n.a.createElement("h3",null,O("Filters"));case s.m.FoldersCreateFolder:return n.a.createElement("h3",null,O("FilterNew"));case s.m.FoldersEditFolder:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,O("FilterEdit")),t&&n.a.createElement(z.a,{className:"settings-more-menu",trigger:f,positionX:"right"},n.a.createElement(q.a,{icon:"delete",destructive:!0,onClick:p},"Delete Folder")));case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement("div",{className:"settings-main-header"},e===s.m.FoldersIncludedChats?n.a.createElement("h3",null,O("FilterInclude")):n.a.createElement("h3",null,O("FilterExclude")),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",className:"color-primary",onClick:c,ariaLabel:O("AutoDeleteConfirm")},n.a.createElement("i",{className:"icon-check"})));default:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,O("SETTINGS")),n.a.createElement(z.a,{className:"settings-more-menu",trigger:f,positionX:"right"},n.a.createElement(q.a,{icon:"logout",onClick:h},O("LogOutTitle"))))}}(),n.a.createElement(Lt.a,{isOpen:i,onClose:b,text:"Are you sure you want to log out?",confirmLabel:"Log Out",confirmHandler:v,confirmIsDestructive:!0}),n.a.createElement(Lt.a,{isOpen:m,onClose:g,text:"Are you sure you want to delete this folder?",confirmLabel:"Delete",confirmHandler:E,confirmIsDestructive:!0}))})),Tt=a(18);var Bt=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e;return{currentUser:t?Object(d.Db)(e,t):void 0}})(({onScreenSelect:e,currentUser:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-main-menu"},t&&n.a.createElement("div",{className:"settings-current-user"},n.a.createElement(U.a,{user:t,size:"jumbo"}),n.a.createElement("p",{className:"name"},Object(m.Y)(t)),n.a.createElement("p",{className:"phone"},Object(Tt.c)(t.phoneNumber))),n.a.createElement(ve.a,{icon:"edit",onClick:()=>e(s.m.EditProfile)},a("EditProfile")),n.a.createElement(ve.a,{icon:"folder",onClick:()=>e(s.m.Folders)},a("Filters")),n.a.createElement(ve.a,{icon:"settings",onClick:()=>e(s.m.General)},a("GeneralSettings")),n.a.createElement(ve.a,{icon:"unmute",onClick:()=>e(s.m.Notifications)},a("Notifications")),n.a.createElement(ve.a,{icon:"lock",onClick:()=>e(s.m.Privacy)},a("PrivacySettings")),n.a.createElement(ve.a,{icon:"language",onClick:()=>e(s.m.Language)},a("Language"))))})),Dt=a(120);a(258);var xt=({isShown:e,className:t,color:a="primary",ariaLabel:c,disabled:r,onClick:s,children:l})=>{const o=Object(ce.a)("FloatingActionButton",e&&"revealed",t);return n.a.createElement(B.a,{className:o,color:a,round:!0,disabled:r,onClick:e&&!r?s:void 0,ariaLabel:c,tabIndex:-1},l)};const Ut=/https:\/\/t\.me\/?/i,Rt=/^([a-zA-Z0-9_]+)$/,Gt=Object(V.a)(e=>e(),250,!1);var zt=Object(n.h)(({currentUsername:e,asLink:t,isLoading:a,isUsernameAvailable:c,checkUsername:r,onChange:s})=>{const[l,o]=Object(n.r)(e||""),i=Object(F.a)(),d=t?"SetUrl":"Username",m=i(t?"SetUrlPlaceholder":"Username"),[u,h]=Object(n.p)(()=>l.length?l.length<5?[void 0,m+" is too short"]:l.length>32?[void 0,m+" is too long"]:Rt.test(l)?void 0===c?[]:[c?i(d+"Available","Username"):void 0,!1===c?i(d+"InUse"):void 0]:[void 0,m+" contains invalid characters"]:[],[l,c,i,d,m]);Object(n.n)(()=>{o(e||"")},[t,e]);const b=Object(n.m)(e=>{const a=e.target.value.trim().replace(Ut,"");o(a),e.target.value=`${t?"https://t.me/":""}${a}`;const n=function(e){return e.length>=5&&e.length<=32&&Rt.test(e)}(a);n&&Gt(()=>{r({username:a})}),s&&s(!!n&&a)},[t,r,s]);return n.a.createElement(pe.a,{value:`${t?"https://t.me/":""}${l}`,onChange:b,label:m,error:h,success:u,readOnly:a})});const qt=Object(V.g)(e=>e(),6e4,!0);var $t=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e,{progress:a,isUsernameAvailable:n}=e.profileEdit||{},c=t?Object(d.Db)(e,t):void 0;if(!c)return{progress:a,isUsernameAvailable:n};const{firstName:r,lastName:s,username:l,fullInfo:o}=c,{bio:i}=o||{};return{currentAvatarHash:Object(m.f)(c),currentFirstName:r,currentLastName:s,currentBio:i,currentUsername:l,progress:a,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["loadCurrentUser","updateProfile","checkUsername"]))(({currentAvatarHash:e,currentFirstName:t,currentLastName:a,currentBio:c,currentUsername:l,progress:o,isUsernameAvailable:i,loadCurrentUser:d,updateProfile:m,checkUsername:u})=>{const[h,b]=Object(n.r)(!1),[p,g]=Object(n.r)(!1),[E,f]=Object(n.r)(),[O,j]=Object(n.r)(),[C,y]=Object(n.r)(t||""),[k,N]=Object(n.r)(a||""),[I,S]=Object(n.r)(c||""),[w,P]=Object(n.r)(l||""),M=Object(v.a)(e,!1,r.ApiMediaFormat.BlobUrl),A=o===s.j.InProgress,T=!1===w,B=Object(n.p)(()=>!T&&(Boolean(O)||p||!0===i),[O,p,T,i]);Object(n.n)(()=>{qt(()=>{d()})},[d]),Object(n.n)(()=>{j(void 0)},[M]),Object(n.n)(()=>{y(t||""),N(a||""),S(c||"")},[t,a,c]),Object(n.n)(()=>{P(l||"")},[l]),Object(n.n)(()=>{o===s.j.Complete&&(g(!1),b(!1),f(void 0))},[o]);const D=Object(n.m)(e=>{j(e)},[]),U=Object(n.m)(e=>{y(e.target.value),g(!0)},[]),R=Object(n.m)(e=>{N(e.target.value),g(!0)},[]),G=Object(n.m)(e=>{S(e.target.value),g(!0)},[]),z=Object(n.m)(e=>{P(e),b(!0)},[]),q=Object(n.m)(()=>{const e=C.trim(),t=k.trim(),a=I.trim();e.length?a.length>70?f("Bio can' be longer than 70 characters"):m({photo:O,...p&&{firstName:e,lastName:t,bio:a},...h&&{username:w}}):f("Please provide your first name")},[O,C,k,I,p,w,h,m]),$=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-edit-profile"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:M,onChange:D,title:"Edit your profile photo",disabled:A}),n.a.createElement(pe.a,{value:C,onChange:U,label:$("FirstName"),disabled:A,error:"Please provide your first name"===E?E:void 0}),n.a.createElement(pe.a,{value:k,onChange:R,label:$("LastName"),disabled:A}),n.a.createElement(pe.a,{value:I,onChange:G,label:$("UserBio"),disabled:A,error:"Bio can' be longer than 70 characters"===E?E:void 0}),n.a.createElement("p",{className:"settings-item-description"},Object(x.a)($("BioAbout"),["br","simple_markdown"]))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},$("Username")),n.a.createElement(zt,{currentUsername:w||"",isLoading:A,isUsernameAvailable:i,checkUsername:u,onChange:z}),n.a.createElement("p",{className:"settings-item-description"},Object(x.a)($("UsernameHelp"),["br","simple_markdown"])),w&&n.a.createElement("p",{className:"settings-item-description"},"This link opens a chat with you:",n.a.createElement("br",null),n.a.createElement("span",{className:"username-link"},"https://t.me/",w)))),n.a.createElement(xt,{isShown:B,onClick:q,disabled:A,ariaLabel:"Save changes"},A?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),Ht=a(116),Vt=a(106);const Yt=Object(V.g)(e=>e(),6e4,!0);var Wt=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a}}=e,{orderedIds:n,byId:c,recommended:r}=e.chatFolders;return{chatsById:t,usersById:a,orderedFolderIds:n,foldersById:c,recommendedChatFolders:r}},(e,t)=>Object(u.l)(t,["loadRecommendedChatFolders","addChatFolder","showError"]))(({onCreateFolder:e,onEditFolder:t,chatsById:a,usersById:c,orderedFolderIds:r,foldersById:s,recommendedChatFolders:o,loadRecommendedChatFolders:i,addChatFolder:d,showError:u})=>{const[h,b]=Object(n.r)(),[p,g]=Object(n.r)(!1),v=Object(n.m)(()=>g(!0),[]);Object(n.n)(()=>{h||Object(Ht.a)("FoldersAll").then(b)},[h]),Object(n.n)(()=>{Yt(()=>{i()})},[i]);const E=Object(n.m)(()=>{Object.keys(s).length>=10?u({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):e()},[s,u,e]),f=Object(F.a)(),O=Object(n.p)(()=>{if(!r)return;const e=Object.keys(a).map(Number);return r.map(t=>{const n=s[t];return{id:n.id,title:n.title,subtitle:Object(m.o)(a,c,n,e,f)}})},[r,a,s,c,f]),j=Object(n.m)(e=>{Object.keys(s).length>=10?u({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):d({folder:e})},[s,d,u]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},h&&n.a.createElement(Vt.a,{id:"settingsFoldersMain",size:l.rb,animationData:h,play:p,noLoop:!0,onLoad:v})),n.a.createElement("p",{className:"settings-item-description mb-3"},f("CreateNewFilterInfo")),n.a.createElement(B.a,{className:"with-icon mb-2",color:"primary",size:"smaller",pill:!0,fluid:!0,onClick:E},n.a.createElement("i",{className:"icon-add"}),f("CreateNewFilter"))),n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},f("Filters")),O&&O.length?O.map(e=>n.a.createElement(ve.a,{className:"mb-2",narrow:!0,multiline:!0,onClick:()=>t(s[e.id])},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.subtitle))):O&&!O.length?n.a.createElement("p",{className:"settings-item-description my-4"},"You have no folders yet."):n.a.createElement(he.a,null)),o&&!!o.length&&n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},f("FilterRecommended")),o.map(e=>n.a.createElement(ve.a,{className:"mb-2",narrow:!0,onClick:()=>j(e)},n.a.createElement("div",{className:"settings-folders-recommended-item"},n.a.createElement("div",{className:"multiline-item"},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.description)),n.a.createElement(B.a,{className:"px-3",color:"primary",size:"tiny",pill:!0,fluid:!0},f("Add")))))))}));a(259);var Kt=({count:e,itemName:t,itemPluralName:a,isLoading:c,onClick:r})=>n.a.createElement(B.a,{className:"ShowMoreButton",color:"translucent",size:"smaller",isText:!0,isLoading:c,onClick:r},n.a.createElement("i",{className:"icon-down"}),"Show ",e," more ",e>1?a||t+"s":t);const Qt="Please provide a title for this folder.",Zt="Please select at least one chat for this folder.";var Xt=Object(n.h)(Object(c.h)(e=>{const{listIds:t}=e.chats;return{loadedActiveChatIds:t.active,loadedArchivedChatIds:t.archived}},(e,t)=>Object(u.l)(t,["editChatFolder","addChatFolder","loadMoreChats"]))(({state:e,dispatch:t,onAddIncludedChats:a,onAddExcludedChats:c,onReset:r,loadedActiveChatIds:s,loadedArchivedChatIds:o,editChatFolder:i,addChatFolder:d,loadMoreChats:h})=>{const[b,p]=Object(n.r)(),[g,v]=Object(n.r)(!1),E=Object(n.m)(()=>v(!0),[]),[f,O]=Object(n.r)(!1),[j,C]=Object(n.r)(!1),{selectedChatIds:y,selectedChatTypes:k}=It(e,"included"),{selectedChatIds:N,selectedChatTypes:I}=It(e,"excluded");Object(n.n)(()=>{b||Object(Ht.a)("FoldersNew").then(p)},[b]),Object(n.n)(()=>{O(!1),C(!1)},[e.folderId]);const[S,w]=Object(n.p)(()=>{const e=new Set([...s||[],...o||[]]),t=Object(u.f)(y,e),a=Object(u.f)(N,e);return[f?t:t.slice(0,5-k.length),j?a:a.slice(0,5-I.length)]},[N,y,k,I,j,f,s,o]);Object(n.n)(()=>{(S.lengthO(!0):()=>C(!0);return n.a.createElement(n.a.Fragment,null,t.map(t=>function(e,t){const a="included"===t?Ct.find(({key:t})=>t===e):yt.find(({key:t})=>t===e);if(a)return n.a.createElement(ve.a,{key:a.key,className:"settings-folders-list-item mb-1",icon:a.icon,narrow:!0,inactive:!0},P(a.title))}(t,e)),a.map(e=>n.a.createElement(ve.a,{className:"settings-folders-list-item mb-1",narrow:!0,inactive:!0},Object(m.kb)(e)?n.a.createElement(Ee.a,{avatarSize:"small",userId:e}):n.a.createElement(fe.a,{avatarSize:"small",chatId:e}))),!c&&r>0&&n.a.createElement(Kt,{count:r,itemName:"chat",onClick:s}))}return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},b&&n.a.createElement(Vt.a,{id:"settingsFoldersEdit",size:l.rb,animationData:b,play:g&&String(e.folderId),noLoop:!0,onLoad:E})),"create"===e.mode&&n.a.createElement("p",{className:"settings-item-description mb-3"},P("FilterIncludeInfo")),n.a.createElement(pe.a,{className:"mb-0",label:P("FilterNameHint"),value:e.folder.title,onChange:function(e){const{currentTarget:a}=e;t({type:"setTitle",payload:a.value.trim()})},error:e.error&&e.error===Qt?Qt:void 0})),n.a.createElement("div",{className:"settings-item no-border pt-3"},e.error&&e.error===Zt&&n.a.createElement("p",{className:"settings-item-description color-danger mb-2"},e.error),n.a.createElement("h4",{className:"settings-item-header mb-3"},P("FilterInclude")),n.a.createElement(ve.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:a},P("FilterAddChats")),M("included")),n.a.createElement("div",{className:"settings-item no-border pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},P("FilterExclude")),n.a.createElement(ve.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:c},P("FilterAddChats")),M("excluded"))),n.a.createElement(xt,{isShown:!!e.isTouched,disabled:e.isLoading,onClick:function(){const{title:a}=e.folder;a?y.length||Object.keys(k).length?(t({type:"setIsLoading",payload:!0}),"edit"===e.mode?i({id:e.folderId,folderUpdate:e.folder}):d({folder:e.folder}),setTimeout(()=>{r()},500)):t({type:"setError",payload:Zt}):t({type:"setError",payload:Qt})},ariaLabel:"edit"===e.mode?"Save changes":"Create folder"},e.isLoading?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),_t=a(41);a(175),a(260);var Jt=Object(n.h)(({mode:e,chatIds:t,selectedIds:a,selectedChatTypes:c,filterValue:r,onSelectedIdsChange:s,onSelectedChatTypesChange:l,onFilterChange:o,onLoadMore:i})=>{const d=Object(n.q)(null),u="included"===e?Ct:yt,h=a.length+c.length>10,b=a.length>=100;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{d.current.focus()})},500)},[]);const p=Object(n.m)(e=>{const t=[...a];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),s(t)},[a,s]),g=Object(n.m)(e=>{const t=[...c];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),l(t)},[c,l]),v=Object(n.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]),E=Object(F.a)();const[f,O]=Object(ue.a)(i,t,Boolean(r));return n.a.createElement("div",{className:"Picker SettingsFoldersChatsPicker"},n.a.createElement("div",{className:"picker-header custom-scroll"},c.map((function(e){const t=u.find(({key:t})=>e===t);if(t)return n.a.createElement(Ze.a,{icon:t.icon,title:E(t.title),isMinimized:h,canClose:!0,onClick:g,clickArg:t.key})})),a.map((e,t)=>n.a.createElement(Ze.a,{chatOrUserId:e,isMinimized:h&&tg(e.key),ripple:!0},n.a.createElement("i",{className:"icon-"+e.icon}),n.a.createElement("h3",{className:"chat-type"},E(e.title)),n.a.createElement(_t.a,{label:"",checked:c.includes(e.key),round:!0}))})),n.a.createElement("div",{key:"divider",className:"picker-list-divider"}),n.a.createElement("h4",{key:"header2",className:"settings-item-header"},E("FilterChats"))),f&&f.length?f.map((function(e){const t=a.includes(e);return n.a.createElement(ve.a,{key:e,className:"chat-item-clickable picker-list-item chat-item",onClick:()=>p(e),ripple:!0,disabled:!t&&b},Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e}):n.a.createElement(fe.a,{chatId:e,withChatType:!0}),n.a.createElement(_t.a,{label:"",checked:t,round:!0}))})):f&&!f.length?n.a.createElement("p",{className:"no-results",key:"no-results"},"Sorry, nothing found."):n.a.createElement(he.a,{key:"loading"})))});var ea=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a,orderedPinnedIds:n}}=e;return{chatsById:t,listIds:a.active,orderedPinnedIds:n.active,archivedPinnedIds:n.archived,archivedListIds:a.archived}},(e,t)=>Object(u.l)(t,["loadMoreChats"]))(({mode:e,state:t,dispatch:a,chatsById:c,listIds:r,orderedPinnedIds:s,archivedListIds:l,archivedPinnedIds:o,loadMoreChats:i})=>{const{chatFilter:d}=t,{selectedChatIds:u,selectedChatTypes:h}=It(t,e,!0),b=Object(n.p)(()=>{const e=r?Object(m.zb)(c,r,s,"all"):void 0,t=l?Object(m.zb)(c,l,o,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[c,r,s,l,o]),p=Object(n.p)(()=>{if(b)return b.filter(e=>!d||Object(me.a)(Object(m.l)(e),d)||u.includes(e.id)).map(({id:e})=>e)},[b,d,u]),g=Object(n.m)(e=>{a({type:"setChatFilter",payload:e})},[a]),v=Object(n.m)(n=>{a("included"===e?{type:"setIncludeFilters",payload:{...t.includeFilters,includedChatIds:n}}:{type:"setExcludeFilters",payload:{...t.excludeFilters,excludedChatIds:n}})},[e,t,a]),E=Object(n.m)(t=>{const n={};t.forEach(e=>{n[e]=!0}),a("included"===e?{type:"setIncludeFilters",payload:{includedChatIds:u,...n}}:{type:"setExcludeFilters",payload:{excludedChatIds:u,...n}})},[e,u,a]);return p?n.a.createElement(Jt,{mode:e,chatIds:p,selectedIds:u,selectedChatTypes:h,filterValue:d,onSelectedIdsChange:v,onSelectedChatTypesChange:E,onFilterChange:g,onLoadMore:i}):n.a.createElement(he.a,null)}));a(261);var ta=Object(n.h)(({currentScreen:e,state:t,dispatch:a,onScreenSelect:c,onReset:r})=>{const l=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{a({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?r():"create"===t.mode?c(s.m.FoldersCreateFolder):c(s.m.FoldersEditFolder)},[t.mode,a,e,r,c]),o=Object(n.m)(()=>{a({type:"reset"}),c(s.m.FoldersCreateFolder)},[c,a]),i=Object(n.m)(e=>{a({type:"editFolder",payload:e}),c(s.m.FoldersEditFolder)},[a,c]),d=Object(n.m)(()=>{a({type:"editIncludeFilters"}),c(s.m.FoldersIncludedChats)},[a,c]),m=Object(n.m)(()=>{a({type:"editExcludeFilters"}),c(s.m.FoldersExcludedChats)},[a,c]);switch(e){case s.m.Folders:return n.a.createElement(Wt,{onCreateFolder:o,onEditFolder:i});case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:return n.a.createElement(Xt,{state:t,dispatch:a,onAddIncludedChats:d,onAddExcludedChats:m,onReset:l});case s.m.FoldersIncludedChats:return n.a.createElement(ea,{mode:"included",state:t,dispatch:a});case s.m.FoldersExcludedChats:return n.a.createElement(ea,{mode:"excluded",state:t,dispatch:a});default:return}}),aa=a(96);a(262);var na=Object(n.h)(({options:e,range:t,label:a,value:c,disabled:r,onChange:s})=>{const l=Object(n.m)(e=>{s(Number(e.currentTarget.value))},[s]),o=Object(ce.a)("RangeSlider",r&&"disabled"),i=Object(n.p)(()=>{if(e)return c/(e.length-1)*100;if(t){const e=(t.max-t.min)/(t.step||1);return(c-t.min)/e*100}return 0},[c,e,t]),[d,m,u]=Object(n.p)(()=>e?[0,e.length-1,1]:t?[t.min,t.max,t.step||1]:[0,0,0],[t,e]);return n.a.createElement("div",{className:o},a&&n.a.createElement("div",{className:"slider-top-row"},n.a.createElement("span",{className:"label"},a),t&&n.a.createElement("span",{className:"value"},c)),n.a.createElement("div",{className:"slider-main"},n.a.createElement("div",{className:"slider-fill-track",style:`width: ${i}%`}),n.a.createElement("input",{min:d,max:m,value:c,step:u,type:"range",onChange:l}),e&&n.a.createElement("div",{className:"slider-options"},e.map((e,t)=>n.a.createElement("div",{className:Object(ce.a)("slider-option no-selection",t===c&&"active"),onClick:()=>s(t)},e)))))}),ca=a(117),ra=a(104),sa=a(44);var la=Object(n.h)(({size:e=l.xb,stickerSet:t,observeIntersection:a})=>{const c=Object(n.q)(null),s=Object(aa.b)(c,a),o="stickerSet"+t.id,i=Object(v.a)(o,!s,r.ApiMediaFormat.Lottie),{shouldRenderFullMedia:d,transitionClassNames:m}=Object(ra.a)(i,"slow");return n.a.createElement("div",{ref:c,className:"sticker-set-cover"},!d&&Object(sa.c)(t.title,2),d&&i&&n.a.createElement(Vt.a,{id:o,size:e,animationData:i,className:m}))});var oa=Object(n.h)(({stickerSet:e,observeIntersection:t})=>{const a=Object(n.q)(null),c=Object(aa.b)(a,t),r=Object(v.a)(e.hasThumbnail&&"stickerSet"+e.id,!c),{shouldRenderFullMedia:s,transitionClassNames:l}=Object(ra.a)(r,"slow");return n.a.createElement("div",{ref:a,className:"sticker-set-cover"},!s&&Object(sa.c)(e.title,2),s&&n.a.createElement("img",{src:r,className:l,alt:""}))});a(263);var ia=Object(n.h)(({sticker:e,size:t,observeIntersection:a,noAnimate:c,title:s,className:l,onClick:o,clickArg:i,onUnfaveClick:d})=>{const m=Object(n.q)(null),{isAnimated:u}=e,h="sticker"+e.id,b="sticker-button-"+e.id,p=Object(aa.b)(m,a),g=e.thumbnail?e.thumbnail.dataUri:void 0,E=Object(v.a)(h+"?size=m",!p,r.ApiMediaFormat.BlobUrl),f=p&&!c,O=Object(v.a)(h,!f,r.ApiMediaFormat.Lottie),[j,C,y]=Object(Ae.a)(Boolean(O)),k=j&&f,{shouldRenderThumb:N,shouldRenderFullMedia:I,transitionClassNames:S}=Object(ra.a)(E||k,"slow");Object(n.n)(()=>{f||y()},[y,f]);const w=Object(ce.a)("StickerButton",u&&"animated",b,l),P=N&&g?`background-image: url('${g}');`:"";return n.a.createElement("div",{ref:m,className:w,title:s||e&&e.emoji,style:P,"data-sticker-id":e.id,onClick:function(){o&&o(i)}},I&&!k&&n.a.createElement("img",{src:E,className:S}),f&&O&&n.a.createElement(Vt.a,{id:h,animationData:O,play:!0,size:t,isLowPriority:!0,onLoad:C}),d&&n.a.createElement(B.a,{className:"sticker-unfave-button",color:"dark",round:!0,onClick:function(t){t.stopPropagation(),t.preventDefault(),d(e)}},n.a.createElement("i",{className:"icon-close"})))});a(264);var da=Object(n.h)(({stickerSet:e,observeIntersection:t,onClick:a})=>{const c=Object(F.a)();if(!e||!e.stickers)return;const r=e.stickers&&e.stickers[0];return e.hasThumbnail||!r?n.a.createElement(ve.a,{narrow:!0,className:"SettingsStickerSet",inactive:!r,onClick:()=>r&&a(r)},n.a.createElement(B.a,{ariaLabel:e.title,color:"translucent"},e.isAnimated?n.a.createElement(la,{size:l.sb,stickerSet:e,observeIntersection:t}):n.a.createElement(oa,{stickerSet:e,observeIntersection:t})),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i")))):n.a.createElement(ve.a,{narrow:!0,className:"SettingsStickerSet",onClick:()=>a(r)},n.a.createElement(ia,{sticker:r,size:l.sb,title:e.title,observeIntersection:t}),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i"))))}),ma=a(153);const ua=o.k?void 0:[{value:"enter",label:"Send by Enter",subLabel:"New line by Shift + Enter"},{value:"ctrl-enter",label:`Send by ${o.e?"Cmd":"Ctrl"} + Enter`,subLabel:"New line by Enter"}],ha=["Solid and Steady","Nice and Fast","Lots of Stuff"];var ba=Object(n.h)(Object(c.h)(e=>({...Object(u.l)(e.settings.byKey,["messageTextSize","animationLevel","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers"]),stickerSetIds:e.stickers.added.setIds,stickerSetsById:e.stickers.setsById}),(e,t)=>Object(u.l)(t,["setSettingOption","loadStickerSets","loadAddedStickers"]))(({onScreenSelect:e,stickerSetIds:t,stickerSetsById:a,messageTextSize:c,animationLevel:r,messageSendKeyCombo:l,shouldAutoDownloadMediaFromContacts:o,shouldAutoDownloadMediaInPrivateChats:i,shouldAutoDownloadMediaInGroups:d,shouldAutoDownloadMediaInChannels:m,shouldAutoPlayGifs:u,shouldAutoPlayVideos:h,shouldSuggestStickers:b,shouldLoopStickers:p,setSettingOption:g,loadStickerSets:v,loadAddedStickers:E})=>{const f=Object(n.q)(null),{observe:O}=Object(aa.a)({rootRef:f}),[j,C,y]=Object(Ae.a)(),[k,N]=Object(n.r)();Object(n.n)(()=>{v()},[v]),Object(n.n)(()=>{t&&t.length&&E()},[t,E]);const I=Object(n.m)(e=>{ha.forEach((t,a)=>{document.body.classList.toggle("animation-level-"+a,e===a)}),g({animationLevel:e})},[g]),S=Object(n.m)(e=>{document.documentElement.style.setProperty("--message-text-size",e+"px"),g({messageTextSize:e})},[g]),w=Object(n.m)(e=>{N(e),C()},[C]),P=Object(F.a)(),M=t&&t.map(e=>!!(a&&a[e]&&a[e].installedDate)&&a[e]).filter(Boolean);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header"},P("SETTINGS")),n.a.createElement(na,{label:P("TextSize"),range:{min:12,max:20},value:c,onChange:S}),n.a.createElement(ve.a,{icon:"photo",onClick:()=>e(s.m.GeneralChatBackground)},P("ChatBackground"))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},"Animation Level"),n.a.createElement("p",{className:"settings-item-description"},"Choose the desired animations amount."),n.a.createElement(na,{options:ha,value:r,onChange:I})),ua&&n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("Keyboard")),n.a.createElement(ca.a,{name:"keyboard-send-settings",options:ua,onChange:e=>g({messageSendKeyCombo:e}),selected:l})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AutoDownloadMedia")),n.a.createElement(_t.a,{label:P("Contacts"),checked:o,onCheck:e=>g({shouldAutoDownloadMediaFromContacts:e})}),n.a.createElement(_t.a,{label:P("AutodownloadPrivateChats"),checked:i,onCheck:e=>g({shouldAutoDownloadMediaInPrivateChats:e})}),n.a.createElement(_t.a,{label:P("AutodownloadGroupChats"),checked:d,onCheck:e=>g({shouldAutoDownloadMediaInGroups:e})}),n.a.createElement(_t.a,{label:P("FilterChannels"),checked:m,onCheck:e=>g({shouldAutoDownloadMediaInChannels:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AutoplayMedia")),n.a.createElement(_t.a,{label:P("GifsTab2"),checked:u,onCheck:e=>g({shouldAutoPlayGifs:e})}),n.a.createElement(_t.a,{label:P("VideosTitle"),checked:h,onCheck:e=>g({shouldAutoPlayVideos:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AccDescrStickers")),n.a.createElement(_t.a,{label:P("SuggestStickers"),checked:b,onCheck:e=>g({shouldSuggestStickers:e})}),n.a.createElement(_t.a,{label:P("LoopAnimatedStickers"),checked:p,onCheck:e=>g({shouldLoopStickers:e})}),n.a.createElement("div",{className:"mt-4",ref:f},M&&M.map(e=>n.a.createElement(da,{key:e.id,stickerSet:e,observeIntersection:O,onClick:w}))),k&&n.a.createElement(ma.a,{isOpen:j,fromSticker:k,onClose:y})))}));let pa;function ga(e="*",t,a=!1){pa||(pa=document.createElement("input"),pa.setAttribute("type","file")),pa.setAttribute("accept",e),a?pa.removeAttribute("multiple"):pa.setAttribute("multiple","multiple"),pa.onchange=null,pa.value="",pa.onchange=t,pa.click()}var va=a(14);function Ea(e){return[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]}function fa(e){const t=e[0].toString(16),a=e[1].toString(16),n=e[2].toString(16);return(1==t.length?"0"+t:t)+(1==a.length?"0"+a:a)+(1==n.length?"0"+n:n)}function Oa([e,t,a]){e/=255,t/=255,a/=255;let n,c,r=Math.max(e,t,a),s=Math.min(e,t,a),l=r,o=r-s;if(c=0==r?0:o/r,r==s)n=0;else{switch(r){case e:n=(t-a)/o+(t.5?Math.max(0,.65*n):Math.max(0,Math.min(1,1-.65*n)),`hsla(${360*t}, ${100*a}%, ${100*n}%, .4)`}var ya=a(13),ka=a(136);a(265);var Na=Object(n.h)(({wallpaper:e,isSelected:t,onClick:a})=>{const{slug:c,document:r}=e,o="wallpaper"+r.id,i=r.previewBlobUrl,d=Object(v.a)(o+"?size=m"),m=Object(ka.a)(r.thumbnail&&r.thumbnail.dataUri,Boolean(d),300),{shouldRenderThumb:u,shouldRenderFullMedia:h,transitionClassNames:b}=Object(ra.a)(d||i,"slow"),[p,g]=Object(n.r)(!1),{mediaData:f,downloadProgress:j}=Object(E.a)(o,!p),C=!1===Object(O.a)(p),{shouldRender:y,transitionClassNames:k}=Object(W.a)(p&&!f||c===s.n,void 0,C,"slow"),N=Object(n.m)(()=>{(async()=>{const e=await Object(va.e)(f);await ya.d(l.l,l.l,e),a(c)})()},[f,a,c]);Object(n.n)(()=>{f&&N()},[f,N]);const I=Object(n.m)(()=>{f?N():g(e=>!e)},[f,N]),S=Object(ce.a)("WallpaperTile",t&&"selected");return n.a.createElement("div",{className:S,onClick:I},n.a.createElement("div",{className:"media-inner"},u&&n.a.createElement("img",{src:m,className:"thumbnail",alt:""}),h&&n.a.createElement("img",{src:d||i,className:"full-media "+b,alt:""}),y&&n.a.createElement("div",{className:Object(ce.a)("spinner-container",k)},n.a.createElement($.a,{progress:j,onClick:I}))))});a(266);const Ia=Object(V.g)(e=>e(),6e4,!0);var Sa=Object(n.h)(Object(c.h)(e=>{const{isBackgroundBlurred:t,customBackground:a}=e.settings.byKey,{loadedWallpapers:n}=e.settings;return{customBackground:a,isBackgroundBlurred:t,loadedWallpapers:n}},(e,t)=>Object(u.l)(t,["setSettingOption","loadWallpapers","uploadWallpaper"]))(({onScreenSelect:e,customBackground:t,isBackgroundBlurred:a,loadedWallpapers:c,setSettingOption:r,loadWallpapers:o,uploadWallpaper:i})=>{Object(n.n)(()=>{Ia(()=>{o()})},[o]);const d=Object(n.m)(e=>{const{files:t}=e.target;t&&t.length>0&&i(t[0])},[i]),m=Object(n.m)(()=>{ga("image/jpeg",d,!0)},[d]),u=Object(n.m)(()=>{e(s.m.GeneralChatBackgroundColor)},[e]),h=Object(n.m)(()=>{r({customBackground:void 0,patternColor:l.s})},[r]),b=Object(n.m)(e=>{r({customBackground:e});const t=c&&c.find(t=>t.slug===e);t&&t.document.thumbnail&&async function(e){const t=[0,0,0];let a,n,c,r,s=-4,l=[0,0,0],o=0;const i=document.createElement("canvas"),d=i.getContext&&i.getContext("2d");if(!d)return t;const m=await Object(va.g)(e);c=m.naturalHeight||m.offsetHeight||m.height,n=m.naturalWidth||m.offsetWidth||m.width,i.height=c,i.width=n,d.drawImage(m,0,0);try{a=d.getImageData(0,0,n,c)}catch(e){return t}for(r=a.data.length;(s+=20){r({patternColor:Ca(e)})})},[c,r]),p=Object(n.m)(e=>{r({isBackgroundBlurred:e.target.checked})},[r]),g=Object(F.a)(),v=c&&c[0]&&c[0].slug===s.n;return n.a.createElement("div",{className:"SettingsGeneralBackground settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(ve.a,{icon:"camera-add",className:"mb-0",disabled:v,onClick:m},g("UploadImage")),n.a.createElement(ve.a,{icon:"colorize",className:"mb-0",onClick:u},g("SetColor")),n.a.createElement(ve.a,{icon:"favorite",onClick:h},g("ThemeResetToDefaults")),n.a.createElement(_t.a,{label:g("BackgroundBlurred"),checked:Boolean(a),onChange:p})),c?n.a.createElement("div",{className:"settings-wallpapers"},c.map(e=>n.a.createElement(Na,{wallpaper:e,isSelected:t===e.slug,onClick:b}))):n.a.createElement(he.a,null))}));a(267);const wa=Oa(Ea("e6ebee")),Pa=["#e6ebee","#b2cee1","#008dd0","#c6e7cb","#c4e1a6","#60b16e","#ccd0af","#a6a997","#7a7072","#fdd7af","#fdb76e","#dd8851"];function Ma(e,t){return{colorPosition:[Math.round(e[1]*(t.colorRect.width-1)),Math.round((1-e[2])*(t.colorRect.height-1))],huePosition:Math.round(e[0]*(t.hueRect.width-1))}}function Fa({colorPosition:e,huePosition:t},a){return[t/(a.hueRect.width-1),e[0]/(a.colorRect.width-1),1-e[1]/(a.colorRect.height-1)]}var La=Object(n.h)(Object(c.h)(e=>({customBackground:e.settings.byKey.customBackground}),(e,t)=>Object(u.l)(t,["setSettingOption"]))(({customBackground:e,setSettingOption:t})=>{const a=Object(n.q)(null),c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(!0),[l,o]=Object(n.r)(function(e){return e&&e.startsWith("#")?Oa(Ea(e.replace("#",""))):wa}(e)),i=Object(n.q)(l);Object(n.n)(()=>{i.current=l},[l]);const[d,m,b]=Object(Ae.a)(),[p,g]=Object(n.r)(""),[v,E]=Object(n.r)(""),f=Object(n.q)(),O=Object(n.q)();Object(n.n)(()=>{const e={offsetLeft:c.current.offsetLeft,...Object(u.l)(c.current.getBoundingClientRect(),["top","width","height"])},t={offsetLeft:r.current.offsetLeft,...Object(u.l)(r.current.getBoundingClientRect(),["width"])};function n(t){const n=[Math.min(Math.max(0,t.pageX-e.offsetLeft),e.width-1),Math.min(Math.max(0,t.pageY-e.top+a.current.scrollTop),e.height-1)],{huePosition:c}=Ma(i.current,f.current);o(Fa({colorPosition:n,huePosition:c},f.current)),m()}function s(e){const{colorPosition:a}=Ma(i.current,f.current),n=Math.min(Math.max(0,e.pageX-t.offsetLeft),t.width-1);o(Fa({colorPosition:a,huePosition:n},f.current)),m()}f.current={colorRect:e,hueRect:t},Object(h.b)(c.current,{onCapture:n,onDrag:n,onRelease:b,onClick:b,withCursor:!0}),Object(h.b)(r.current,{onCapture:s,onDrag:s,onRelease:b,onClick:b,withCursor:!0})},[m,b]);const{colorPosition:j=[0,0],huePosition:C=0}=f.current?Ma(l,f.current):{},y=fa(ja(l)),k=l[0],N=fa(ja([k,1,1]));Object(n.n)(()=>{const e=ja(l),a="#"+fa(e);g(e.join(", ")),E(a),s.current||t({customBackground:a,patternColor:Ca(e)}),s.current=!1},[l,t]),Object(n.n)(()=>{!function(e,t,a,n){let c,r,s;a.current&&n.current?(c=n.current.colorRect.width,r=n.current.colorRect.height,s=a.current):(c=e.offsetWidth,r=e.offsetHeight,s=e.getContext("2d"),e.width=c,e.height=r,a.current=s);const l=s.createImageData(c,r),o=l.data,i=ja([t,1,1]);let d=0;for(let e=0;e{!function(e){const t=e.offsetWidth;e.width=t,e.height=1;const a=e.getContext("2d"),n=a.createImageData(t,1),c=n.data;let r=0;for(let e=0;e{const t=e.currentTarget.value.replace(/[^\d, ]/g,"").slice(0,13);if(t.match(/^\d{1,3},\s?\d{1,3},\s?\d{1,3}$/)){const e=t.split(",").map(e=>Number(e.trim()));o(Oa(e))}e.currentTarget.value=t},[]),S=Object(n.m)(e=>{const t=e.currentTarget.value.replace(/[^0-9a-fA-F]/g,"").slice(0,6);t.match(/^#?[0-9a-fA-F]{6}$/)&&o(Oa(Ea(t.replace("#","")))),e.currentTarget.value=t},[]),w=Object(n.m)(e=>{o(Oa(Ea(e.currentTarget.dataset.color.replace("#",""))))},[]),P=Object(ce.a)("SettingsGeneralBackgroundColor settings-content custom-scroll",d&&"is-dragging");return n.a.createElement("div",{ref:a,className:P},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("div",{ref:c,className:"color-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translate(${j[0]}px, ${j[1]}px); background-color: #${y};`})),n.a.createElement("div",{ref:r,className:"hue-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translateX(${C}px); background-color: #${N};`})),n.a.createElement("div",{className:"tools"},n.a.createElement(pe.a,{value:v,label:"HEX",onChange:S}),n.a.createElement(pe.a,{value:p,label:"RGB",onChange:I}))),n.a.createElement("div",{className:"predefined-colors"},Pa.map(e=>n.a.createElement("div",{className:e==="#"+y?"active":void 0,"data-color":e,style:`background-color: ${e};`,onClick:w}))))}));var Aa=Object(n.h)(Object(c.h)(e=>({hasPrivateChatsNotifications:Boolean(e.settings.byKey.hasPrivateChatsNotifications),hasPrivateChatsMessagePreview:Boolean(e.settings.byKey.hasPrivateChatsMessagePreview),hasGroupNotifications:Boolean(e.settings.byKey.hasGroupNotifications),hasGroupMessagePreview:Boolean(e.settings.byKey.hasGroupMessagePreview),hasBroadcastNotifications:Boolean(e.settings.byKey.hasBroadcastNotifications),hasBroadcastMessagePreview:Boolean(e.settings.byKey.hasBroadcastMessagePreview),hasContactJoinedNotifications:Boolean(e.settings.byKey.hasContactJoinedNotifications)}),(e,t)=>Object(u.l)(t,["loadNotificationsSettings","updateContactSignUpNotification","updateNotificationSettings"]))(({hasPrivateChatsNotifications:e,hasPrivateChatsMessagePreview:t,hasGroupNotifications:a,hasGroupMessagePreview:c,hasBroadcastNotifications:r,hasBroadcastMessagePreview:s,hasContactJoinedNotifications:l,loadNotificationsSettings:o,updateContactSignUpNotification:i,updateNotificationSettings:d})=>{Object(n.n)(()=>{o()},[o]);const m=Object(n.m)((n,l,o)=>{const i="contact"===l?!e:!("group"===l?a:r),m="contact"===l?t:"group"===l?c:s;d({peerType:l,..."silent"===o&&{isSilent:!n.target.checked,isShowPreviews:m},..."showPreviews"===o&&{isShowPreviews:n.target.checked,isSilent:i}})},[s,r,c,a,t,e,d]),u=Object(n.m)(e=>{i({isSilent:!e.target.checked})},[i]),h=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("AutodownloadPrivateChats")),n.a.createElement(_t.a,{label:h("NotificationsForPrivateChats"),subLabel:h(e?"NotificationsEnabled":"NotificationsDisabled"),checked:e,onChange:e=>{m(e,"contact","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(t?"PreviewEnabled":"PreviewDisabled"),checked:t,onChange:e=>{m(e,"contact","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("FilterGroups")),n.a.createElement(_t.a,{label:h("NotificationsForGroups"),subLabel:h(a?"NotificationsEnabled":"NotificationsDisabled"),checked:a,onChange:e=>{m(e,"group","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(c?"PreviewEnabled":"PreviewDisabled"),checked:c,onChange:e=>{m(e,"group","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("FilterChannels")),n.a.createElement(_t.a,{label:h("NotificationsForChannels"),subLabel:h(r?"NotificationsEnabled":"NotificationsDisabled"),checked:r,onChange:e=>{m(e,"broadcast","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(s?"PreviewEnabled":"PreviewDisabled"),checked:s,onChange:e=>{m(e,"broadcast","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("PhoneOther")),n.a.createElement(_t.a,{label:h("ContactJoined"),checked:l,onChange:u})))}));var Ta=Object(n.h)(Object(c.h)(e=>{const{settings:{byKey:{hasPassword:t},privacy:a},blocked:n,activeSessions:c}=e;return{hasPassword:t,blockedCount:n.totalCount,sessionsCount:c.length,visibilityPrivacyPhoneNumber:a.phoneNumber&&a.phoneNumber.visibility,visibilityPrivacyLastSeen:a.lastSeen&&a.lastSeen.visibility,visibilityPrivacyProfilePhoto:a.profilePhoto&&a.profilePhoto.visibility,visibilityPrivacyForwarding:a.forwards&&a.forwards.visibility,visibilityPrivacyGroupChats:a.chatInvite&&a.chatInvite.visibility}},(e,t)=>Object(u.l)(t,["loadBlockedContacts","loadAuthorizations","loadPrivacySettings"]))(({onScreenSelect:e,hasPassword:t,blockedCount:a,sessionsCount:c,visibilityPrivacyPhoneNumber:r,visibilityPrivacyLastSeen:l,visibilityPrivacyProfilePhoto:o,visibilityPrivacyForwarding:i,visibilityPrivacyGroupChats:d,loadPrivacySettings:m,loadBlockedContacts:u,loadAuthorizations:h})=>{Object(n.n)(()=>{u(),h(),m()},[u,h,m]);const b=Object(F.a)();function p(e){switch(e){case"everybody":return b("P2PEverybody");case"contacts":return b("P2PContacts");case"nobody":return b("P2PNobody")}}return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(ve.a,{icon:"delete-user",narrow:!0,onClick:()=>e(s.m.PrivacyBlockedUsers)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("BlockedUsers")),a>0&&n.a.createElement("span",{className:"subtitle"},b("Users",a)))),n.a.createElement(ve.a,{icon:"lock",narrow:!0,onClick:()=>e(t?s.m.TwoFaEnabled:s.m.TwoFaDisabled)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("TwoStepVerification")),n.a.createElement("span",{className:"subtitle"},b(t?"PasswordOn":"PasswordOff")))),n.a.createElement(ve.a,{icon:"active-sessions",narrow:!0,onClick:()=>e(s.m.PrivacyActiveSessions)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("SessionsTitle")),c>0&&n.a.createElement("span",{className:"subtitle"},1===c?"1 session":c+" sessions")))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},b("PrivacyTitle")),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyPhoneNumber)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyPhoneTitle")),n.a.createElement("span",{className:"subtitle"},p(r)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyLastSeen)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("LastSeenTitle")),n.a.createElement("span",{className:"subtitle"},p(l)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyProfilePhoto)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyProfilePhotoTitle")),n.a.createElement("span",{className:"subtitle"},p(o)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyForwarding)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyForwardsTitle")),n.a.createElement("span",{className:"subtitle"},p(i)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyGroupChats)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("WhoCanAddMe")),n.a.createElement("span",{className:"subtitle"},p(d))))))}));var Ba=Object(n.h)(Object(c.h)(e=>({languages:e.settings.byKey.languages,language:e.settings.byKey.language}),(e,t)=>Object(u.l)(t,["loadLanguages","setSettingOption"]))(({languages:e,language:t,loadLanguages:a,setSettingOption:c})=>{const[r,s]=Object(n.r)(t),[l,o,i]=Object(Ae.a)();Object(n.n)(()=>{a()},[a]);const d=Object(n.m)(e=>{s(e),o(),Object(Xe.c)(e,()=>{i(),c({language:e})})},[o,i,c]),m=Object(n.p)(()=>e?function(e){return e.map(({langCode:e,nativeName:t,name:a})=>({value:e,label:t,subLabel:a}))}(e):void 0,[e]);return n.a.createElement("div",{className:"settings-content settings-item settings-language custom-scroll"},m?n.a.createElement(ca.a,{name:"keyboard-send-settings",options:m,selected:r,loadingOption:l?r:void 0,onChange:d}):n.a.createElement(he.a,null))}));function Da(e){switch(e){case s.m.PrivacyPhoneNumber:case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return"phoneNumber";case s.m.PrivacyLastSeen:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return"lastSeen";case s.m.PrivacyProfilePhoto:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return"profilePhoto";case s.m.PrivacyForwarding:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return"forwards";case s.m.PrivacyGroupChats:case s.m.PrivacyGroupChatsAllowedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return"chatInvite"}}var xa=Object(n.h)(Object(c.h)((e,{screen:t})=>{let a;const{chats:{byId:n},settings:{privacy:c}}=e;switch(t){case s.m.PrivacyPhoneNumber:a=c.phoneNumber;break;case s.m.PrivacyLastSeen:a=c.lastSeen;break;case s.m.PrivacyProfilePhoto:a=c.profilePhoto;break;case s.m.PrivacyForwarding:a=c.forwards;break;case s.m.PrivacyGroupChats:a=c.chatInvite}return a?{...a,chatsById:n}:{}},(e,t)=>Object(u.l)(t,["setPrivacyVisibility"]))(({screen:e,onScreenSelect:t,visibility:a,allowUserIds:c,allowChatIds:r,blockUserIds:l,blockChatIds:o,chatsById:i,setPrivacyVisibility:d})=>{const m=Object(F.a)(),u=Object(n.p)(()=>{switch(e){case s.m.PrivacyProfilePhoto:case s.m.PrivacyGroupChats:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")}];default:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")},{value:"nobody",label:m("P2PNobody")}]}},[m,e]),h={shouldShowDenied:"nobody"!==a,shouldShowAllowed:"everybody"!==a},b=Da(e),p=Object(n.p)(()=>{switch(e){case s.m.PrivacyPhoneNumber:return m("PrivacyPhoneTitle");case s.m.PrivacyLastSeen:return m("LastSeenTitle");case s.m.PrivacyProfilePhoto:return m("PrivacyProfilePhotoTitle");case s.m.PrivacyForwarding:return m("PrivacyForwardsTitle");case s.m.PrivacyGroupChats:return m("WhoCanAddMe");default:return}},[m,e]),g=Object(n.p)(()=>{switch(e){case s.m.PrivacyLastSeen:return m("CustomHelp");default:return}},[m,e]),v=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberAllowedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenAllowedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoAllowedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingAllowedContacts;default:return s.m.PrivacyGroupChatsAllowedContacts}})(),E=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberDeniedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenDeniedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoDeniedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingDeniedContacts;default:return s.m.PrivacyGroupChatsDeniedContacts}})(),f=Object(n.p)(()=>c&&r&&i?r.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),c.length):0,[r,c,i]),O=Object(n.p)(()=>l&&o&&i?o.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),l.length):0,[o,l,i]),j=Object(n.m)(e=>{d({privacyKey:b,visibility:e})},[b,d]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},p),n.a.createElement(ca.a,{name:"visibility-"+b,options:u,onChange:j,selected:a}),g&&n.a.createElement("p",{className:"settings-item-description-larger"},g)),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},m("PrivacyExceptions")),h.shouldShowAllowed&&n.a.createElement(ve.a,{narrow:!0,icon:"add-user",onClick:()=>{t(v)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},f>0&&n.a.createElement("span",{className:"date"},"+",f),n.a.createElement("span",{className:"title"},m("AlwaysShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers")))),h.shouldShowDenied&&n.a.createElement(ve.a,{narrow:!0,icon:"delete-user",onClick:()=>{t(E)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},O>0&&n.a.createElement("span",{className:"date"},"−",O),n.a.createElement("span",{className:"title"},m("NeverShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers"))))))}));function Ua(e){return[e.region,e.country].filter(Boolean).join(", ")}function Ra(e){return`${e.deviceModel}${e.deviceModel?", ":""} ${e.platform} ${e.systemVersion}`}var Ga=Object(n.h)(Object(c.h)(e=>({activeSessions:e.activeSessions}),(e,t)=>Object(u.l)(t,["loadAuthorizations","terminateAuthorization","terminateAllAuthorizations"]))(({activeSessions:e,loadAuthorizations:t,terminateAuthorization:a,terminateAllAuthorizations:c})=>{const[r,s,l]=Object(Ae.a)();Object(n.n)(()=>{t()},[t]);const o=Object(n.m)(e=>{a({hash:e})},[a]),i=Object(n.m)(()=>{l(),c()},[l,c]),d=Object(n.p)(()=>e.find(e=>e.isCurrent),[e]),m=Object(n.p)(()=>e.filter(e=>!e.isCurrent),[e]),u=Object(F.a)();function h(e){return n.a.createElement(ve.a,{key:e.hash,ripple:!0,narrow:!0,contextActions:[{title:"Terminate",icon:"stop",handler:()=>{o(e.hash)}}]},n.a.createElement("div",{className:"multiline-menu-item full-size"},n.a.createElement("span",{className:"date"},Object(D.g)(1e3*e.dateActive)),n.a.createElement("span",{className:"title"},e.appName),n.a.createElement("span",{className:"subtitle black tight"},Ra(e)),n.a.createElement("span",{className:"subtitle"},e.ip," - ",Ua(e))))}return n.a.createElement("div",{className:"settings-content custom-scroll"},d&&(p=d,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},u("AuthSessions.CurrentSession")),n.a.createElement(ve.a,{narrow:!0,inactive:!0},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},p.appName),n.a.createElement("span",{className:"subtitle black tight"},Ra(p)),n.a.createElement("span",{className:"subtitle"},p.ip," - ",Ua(p)))),n.a.createElement(ve.a,{className:"destructive mb-0",icon:"stop",ripple:!0,narrow:!0,onClick:s},u("TerminateAllSessions")))),m&&(b=m,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},"Other Sessions"),b.map(h))),m&&n.a.createElement(Lt.a,{isOpen:r,onClose:l,text:"Are you sure you want to terminate all other sessions?",confirmLabel:"Terminate All Other Sessions",confirmHandler:i,confirmIsDestructive:!0}),";");var b,p}));var za=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a},blocked:{ids:n}}=e;return{chatsByIds:t,usersByIds:a,blockedIds:n}},(e,t)=>Object(u.l)(t,["unblockContact"]))(({chatsByIds:e,usersByIds:t,blockedIds:a,unblockContact:c})=>{const r=Object(n.m)(e=>{c({contactId:e})},[c]),s=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content infinite-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("p",{className:"settings-item-description-larger mt-0 mb-2"},s("BlockedUsersInfo"))),n.a.createElement("div",{className:"chat-list custom-scroll"},a&&a.length?n.a.createElement("div",{className:"scroll-container"},a.map((a,c)=>function(a,c,s){const o=Object(m.kb)(a),i=o?t[a]:void 0,d=o?void 0:e[a],u=Object(ce.a)("Chat chat-item-clickable blocked-list-item",o?"private":"group");return n.a.createElement(ve.a,{key:a,className:u,ripple:!0,narrow:!0,contextActions:[{title:"Unblock",icon:"unlock",handler:()=>{r(a)}}],style:`top: ${(s+c)*l.h}px;`},n.a.createElement(U.a,{size:"medium",user:i,chat:d}),n.a.createElement("div",{className:"contact-info"},n.a.createElement("h3",null,Object(x.a)((o?Object(m.Y)(i):Object(m.l)(d))||"")),i&&i.phoneNumber&&n.a.createElement("div",{className:"contact-phone"},Object(Tt.c)(i.phoneNumber)),i&&!i.phoneNumber&&i.username&&n.a.createElement("div",{className:"contact-username"},"@",i.username)))}(a,c,0))):a&&!a.length?n.a.createElement("div",{className:"no-results"},"List is empty"):n.a.createElement(he.a,{key:"loading"}))),n.a.createElement(xt,{isShown:!0,onClick:()=>{},className:"not-implemented",ariaLabel:"Add a blocked user"},n.a.createElement("i",{className:"icon-add"})))})),qa=a(119);var $a=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},Object(x.a)(a("EnabledPasswordText"),["br"]))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(ve.a,{icon:"edit",onClick:()=>t(s.m.TwoFaChangePasswordCurrent)},a("ChangePassword")),n.a.createElement(ve.a,{icon:"password-off",onClick:()=>t(s.m.TwoFaTurnOff)},a("TurnPasswordOff")),n.a.createElement(ve.a,{icon:"email",onClick:()=>t(s.m.TwoFaRecoveryEmailCurrentPassword)},a("SetRecoveryEmail"))))})),Ha=a(138),Va=a(139);var Ya=Object(n.h)(({error:e,isLoading:t,expectedPassword:a,placeholder:c="Current Password",hint:r,submitLabel:s,clearError:l,onSubmit:o})=>{const[i,d]=Object(n.r)(""),[m,u]=Object(n.r)(!1),h=Object(n.m)(e=>{a&&e!==a?d("Passwords Should Be Equal"):o(e)},[o,a]),b=Object(n.m)(()=>{l&&l(),d("")},[l]),p=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Ha.a,{isBig:!0,isPasswordVisible:m})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Va.a,{error:i||e,hint:r,placeholder:c,submitLabel:s||p("Next"),clearError:b,isLoading:t,isPasswordVisible:m,onChangePasswordVisibility:u,onSubmit:h})))});var Wa=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onStart:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},a("SetAdditionalPasswordInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(B.a,{onClick:t},a("EditAdminTransferSetPassword"))))}));const Ka=o.f?550:400;var Qa=Object(n.h)(Object(c.h)((e,{icon:t})=>({animatedEmoji:Object(d.c)(e,"email"===t?"💌":"💡")}))(({animatedEmoji:e,type:t="text",isLoading:a,error:c,placeholder:r,shouldConfirm:s,clearError:l,onSubmit:i})=>{const d=Object(n.q)(null),[m,u]=Object(n.r)(""),[h,b,p]=Object(Ae.a)(!1);Object(n.n)(()=>{o.k||setTimeout(()=>{d.current.focus()},Ka)},[]);const g=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement("form",{action:"",onSubmit:e=>{e.preventDefault(),d.current&&i(m)}},n.a.createElement(pe.a,{ref:d,value:m,inputMode:t,label:r,error:c,onChange:e=>{c&&l&&l(),u(e.target.value)}}),m?n.a.createElement(B.a,{type:"submit",isLoading:a,ripple:!0},g("Continue")):n.a.createElement(B.a,{isText:!0,isLoading:a,ripple:!0,onClick:s?b:()=>{i()}},g("YourEmailSkip"))),s&&n.a.createElement(be.a,{className:"narrow",isOpen:h,title:g("YourEmailSkipWarning"),onClose:p},Object(x.a)(g("YourEmailSkipWarningText"),["br","simple_markdown"]),n.a.createElement("div",{className:"dialog-buttons"},n.a.createElement(B.a,{color:"danger",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:()=>{p(),i()}},g("YourEmailSkip")),n.a.createElement(B.a,{color:"primary",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:p},g("Cancel"))))))}));var Za=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🥳")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},a("TwoStepVerificationPasswordSetInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(B.a,{onClick:()=>{t(s.m.Privacy)}},a("TwoStepVerificationPasswordReturnSettings"))))}));const Xa=o.f?550:400;var _a=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"💌"),codeLength:e.twoFaSettings.waitingEmailCodeLength}))(({animatedEmoji:e,codeLength:t,isLoading:a,error:c,clearError:r,onSubmit:s})=>{const l=Object(n.q)(null),[i,d]=Object(n.r)("");Object(n.n)(()=>{o.k||setTimeout(()=>{l.current.focus()},Xa)},[]);const m=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(pe.a,{value:i,ref:l,inputMode:"decimal",label:m("YourEmailCode"),error:c,onChange:e=>{c&&r&&r();const a=e.target.value.slice(0,t);a.length===t&&s(a),d(a),e.target.value=a}}),a&&n.a.createElement(he.a,null)))}));var Ja=Object(n.h)(Object(c.h)(e=>({...e.twoFaSettings}),(e,t)=>Object(u.l)(t,["updatePassword","updateRecoveryEmail","clearPassword","provideTwoFaEmailCode","checkPassword","clearTwoFaError"]))(({currentScreen:e,state:t,hint:a,isLoading:c,error:r,waitingEmailCodeLength:l,dispatch:o,onScreenSelect:i,updatePassword:d,checkPassword:m,clearTwoFaError:u,updateRecoveryEmail:h,provideTwoFaEmailCode:b,clearPassword:p})=>{Object(n.n)(()=>{l&&(e===s.m.TwoFaNewPasswordEmail?i(s.m.TwoFaNewPasswordEmailCode):e===s.m.TwoFaRecoveryEmail&&i(s.m.TwoFaRecoveryEmailCode))},[e,i,l]);const g=Object(n.m)(()=>{o({type:"reset"}),i(s.m.TwoFaNewPassword)},[o,i]),v=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaNewPasswordConfirm)},[o,i]),E=Object(n.m)(()=>{i(s.m.TwoFaNewPasswordHint)},[i]),f=Object(n.m)(e=>{o({type:"setHint",payload:e}),i(s.m.TwoFaNewPasswordEmail)},[o,i]),O=Object(n.m)(e=>{o({type:"setEmail",payload:e}),d({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),j=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaChangePasswordNew)}})},[m,o,i]),C=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaChangePasswordConfirm)},[o,i]),y=Object(n.m)(()=>{i(s.m.TwoFaChangePasswordHint)},[i]),k=Object(n.m)(e=>{o({type:"setHint",payload:e}),d({...t,hint:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),N=Object(n.m)(e=>{p({currentPassword:e,onSuccess:()=>{i(s.m.Privacy)}})},[p,i]),I=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaRecoveryEmail)}})},[m,o,i]),S=Object(n.m)(e=>{o({type:"setEmail",payload:e}),h({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,h]),w=Object(n.m)(e=>{b({code:e})},[b]),P=Object(F.a)();switch(e){case s.m.TwoFaDisabled:return n.a.createElement(Wa,{onStart:g});case s.m.TwoFaNewPassword:return n.a.createElement(Ya,{placeholder:P("EnterPassword"),submitLabel:P("Continue"),onSubmit:v});case s.m.TwoFaNewPasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),submitLabel:P("Continue"),onSubmit:E});case s.m.TwoFaNewPasswordHint:return n.a.createElement(Qa,{icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:f});case s.m.TwoFaNewPasswordEmail:return n.a.createElement(Qa,{icon:"email",type:"email",isLoading:c,error:r,clearError:u,placeholder:P("RecoveryEmailTitle"),shouldConfirm:!0,onSubmit:O});case s.m.TwoFaNewPasswordEmailCode:return n.a.createElement(_a,{isLoading:c,error:r,clearError:u,onSubmit:w});case s.m.TwoFaCongratulations:return n.a.createElement(Za,{onScreenSelect:i});case s.m.TwoFaEnabled:return n.a.createElement($a,{onScreenSelect:i});case s.m.TwoFaChangePasswordCurrent:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:j});case s.m.TwoFaChangePasswordNew:return n.a.createElement(Ya,{placeholder:P("PleaseEnterNewFirstPassword"),onSubmit:C});case s.m.TwoFaChangePasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),onSubmit:y});case s.m.TwoFaChangePasswordHint:return n.a.createElement(Qa,{isLoading:c,error:r,clearError:u,icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:k});case s.m.TwoFaTurnOff:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:N});case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:I});case s.m.TwoFaRecoveryEmail:return n.a.createElement(Qa,{icon:"email",type:"email",placeholder:P("RecoveryEmailTitle"),onSubmit:S});case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(_a,{isLoading:c,error:r,clearError:u,onSubmit:w});default:return}}));var en=Object(n.h)(({itemIds:e,selectedIds:t,filterValue:a,filterPlaceholder:c,notFoundText:r,searchInputId:s,isLoading:l,onSelectedIdsChange:o,onFilterChange:i,onLoadMore:d})=>{const u=Object(n.q)(null),h=t.length>10;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{u.current.focus()})},500)},[]);const b=Object(n.m)(e=>{const a=[...t];a.includes(e)?a.splice(a.indexOf(e),1):a.push(e),o(a),i("")},[t,o,i]),p=Object(n.m)(e=>{const{value:t}=e.currentTarget;i(t)},[i]),[g,v]=Object(ue.a)(d,e,Boolean(a)),E=Object(F.a)();return n.a.createElement("div",{className:"Picker"},n.a.createElement("div",{className:"picker-header custom-scroll"},t.map((e,a)=>n.a.createElement(Ze.a,{chatOrUserId:e,isMinimized:h&&an.a.createElement(ve.a,{key:e,className:"chat-item-clickable picker-list-item",onClick:()=>b(e),ripple:!0},n.a.createElement(_t.a,{label:"",checked:t.includes(e)}),Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e}):n.a.createElement(fe.a,{chatId:e})))):l||!g||g.length?n.a.createElement(he.a,null):n.a.createElement("p",{className:"no-results"},r||"Sorry, nothing found."))});function tn(e,t){const{privacy:a}=e.settings;switch(t){case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return a.phoneNumber;case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return a.lastSeen;case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return a.profilePhoto;case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return a.forwards;case s.m.PrivacyGroupChatsDeniedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return a.chatInvite}}var an=Object(n.h)(Object(c.h)((e,{screen:t})=>{const{chats:{byId:a,listIds:n,orderedPinnedIds:c},currentUserId:r}=e;return{currentUserId:r,chatsById:a,listIds:n.active,orderedPinnedIds:c.active,archivedPinnedIds:c.archived,archivedListIds:n.archived,settings:tn(e,t)}},(e,t)=>Object(u.l)(t,["setPrivacySettings"]))(({currentUserId:e,isAllowList:t,screen:a,settings:c,chatsById:r,listIds:l,orderedPinnedIds:o,archivedListIds:i,archivedPinnedIds:d,setPrivacySettings:u,onScreenSelect:h})=>{const b=Object(n.p)(()=>c?t?[...c.allowUserIds,...c.allowChatIds]:[...c.blockUserIds,...c.blockChatIds]:[],[t,c]),[p,g]=Object(n.r)(""),[v,E]=Object(n.r)(!1),[f,O]=Object(n.r)(b),j=Object(n.p)(()=>{const e=l?Object(m.zb)(r,l,o,"all"):void 0,t=i?Object(m.zb)(r,i,d,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[r,l,o,i,d]),C=Object(n.p)(()=>{if(j)return j.filter(t=>(Object(m.kb)(t.id)&&t.id!==e||Object(m.jb)(t))&&(!p||Object(me.a)(Object(m.l)(t),p)||b.includes(t.id))).map(({id:e})=>e)},[j,e,p,b]),y=Object(n.m)(e=>{O(e),E(!0)},[]),k=Object(n.m)(()=>{u({privacyKey:Da(a),isAllowList:Boolean(t),contactsIds:f}),h(s.m.Privacy)},[t,f,h,a,u]),N=Object(F.a)();return n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(en,{itemIds:C||[],selectedIds:f,filterValue:p,filterPlaceholder:N(t?"AlwaysShareWithPlaceholder":"NeverShareWithPlaceholder"),searchInputId:"new-group-picker-search",onSelectedIdsChange:y,onFilterChange:g}),n.a.createElement(xt,{isShown:v,onClick:k,ariaLabel:N(t?"AlwaysShareWithTitle":"NeverShareWithTitle")},n.a.createElement("i",{className:"icon-arrow-right"})))}));a(268);const nn=Object.keys(s.m).length/2;var cn=Object(n.h)(({currentScreen:e,onScreenSelect:t,onReset:a})=>{const[c,r]=jt(Pt,wt),[l,i]=jt(Ft,Mt),d=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{r({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?a():"create"===c.mode?t(s.m.FoldersCreateFolder):t(s.m.FoldersEditFolder)},[c.mode,r,e,a,t]),m=Object(n.m)(()=>{r({type:"saveFilters"}),d()},[r,d]);function u(){return n.a.createElement(n.a.Fragment,null,n.a.createElement(At,{currentScreen:e,onReset:d,onSaveFilter:m,editedFolderId:c.folderId}),function(){switch(e){case s.m.Main:return n.a.createElement(Bt,{onScreenSelect:t});case s.m.EditProfile:return n.a.createElement($t,null);case s.m.General:return n.a.createElement(ba,{onScreenSelect:t});case s.m.Notifications:return n.a.createElement(Aa,null);case s.m.Privacy:return n.a.createElement(Ta,{onScreenSelect:t});case s.m.Language:return n.a.createElement(Ba,null);case s.m.GeneralChatBackground:return n.a.createElement(Sa,{onScreenSelect:t});case s.m.GeneralChatBackgroundColor:return n.a.createElement(La,{onScreenSelect:t});case s.m.PrivacyActiveSessions:return n.a.createElement(Ga,null);case s.m.PrivacyBlockedUsers:return n.a.createElement(za,null);case s.m.PrivacyPhoneNumber:case s.m.PrivacyLastSeen:case s.m.PrivacyProfilePhoto:case s.m.PrivacyForwarding:case s.m.PrivacyGroupChats:return n.a.createElement(xa,{screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement(an,{isAllowList:!0,screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement(an,{screen:e,onScreenSelect:t});case s.m.Folders:case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement(ta,{currentScreen:e,state:c,dispatch:r,onScreenSelect:t,onReset:d});case s.m.TwoFaDisabled:case s.m.TwoFaNewPassword:case s.m.TwoFaNewPasswordConfirm:case s.m.TwoFaNewPasswordHint:case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaCongratulations:case s.m.TwoFaEnabled:case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:case s.m.TwoFaChangePasswordHint:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:case s.m.TwoFaRecoveryEmail:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(Ja,{currentScreen:e,state:l,dispatch:i,onScreenSelect:t});default:return}}())}return n.a.createElement(T.a,{id:"Settings",name:o.f?"slide-layers":"push-slide",activeKey:e,renderCount:nn},u)});const rn=Object(V.g)(e=>e(),6e4,!0);var sn=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users;return{usersById:a,contactIds:t}},(e,t)=>Object(u.l)(t,["loadContactList","openChat"]))(({filter:e,usersById:t,contactIds:a,loadContactList:c,openChat:r})=>{Object(n.n)(()=>{rn(()=>{c()})});const s=Object(n.m)(e=>{r({id:e})},[r]),l=Object(n.p)(()=>{if(!a)return;const n=e?a.filter(a=>{const n=t[a];if(!n)return!1;const c=Object(m.Y)(n);return c&&Object(me.a)(c,e)}):a;return Object(m.Cb)(n,t)},[e,t,a]),[i,d]=Object(ue.a)(void 0,l,Boolean(e));return n.a.createElement(ge.a,{items:i,onLoadMore:d,className:"chat-list custom-scroll"},i&&i.length?i.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable",onClick:()=>s(e),ripple:!o.f},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0,avatarSize:"large"}))):i&&!i.length?n.a.createElement("p",{className:"no-results",key:"no-results"},e.length?"No contacts matched your search.":"Contact list is empty."):n.a.createElement(he.a,{key:"loading"}))}));const ln=Object(V.g)(e=>e(),6e4,!0);var on=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users,{byId:n}=e.chats,{currentUserId:c}=e,{query:r,fetchingStatus:s,globalResults:l,localResults:o}=e.globalSearch,{userIds:i}=l||{},{userIds:d}=o||{};return{currentUserId:c,usersById:a,chatsById:n,localContactIds:t,searchQuery:r,isSearching:s&&s.chats,globalUserIds:i,localUserIds:d}},(e,t)=>Object(u.l)(t,["loadContactList","setGlobalSearchQuery"]))(({isChannel:e,selectedMemberIds:t,onSelectedMemberIdsChange:a,onNextStep:c,onReset:r,currentUserId:s,usersById:l,chatsById:o,localContactIds:i,searchQuery:d,isSearching:h,localUserIds:b,globalUserIds:p,loadContactList:g,setGlobalSearchQuery:v})=>{Object(n.n)(()=>{ln(()=>{g()})});const E=Object(n.m)(e=>{v({query:e})},[v]),f=Object(n.p)(()=>{const e=i?Object(m.Bb)(i.filter(e=>e!==s),o):[];if(!d)return e;const a=e.filter(e=>{const t=l[e];if(!t)return!1;const a=Object(m.Y)(t);return a&&Object(me.a)(a,d)});return Object(m.Bb)(Object(u.o)([...a,...b||[],...p||[]]),o,!1,t)},[i,d,b,p,l,o,t,s]),O=Object(n.m)(()=>{t.length&&(v({query:""}),c())},[t,v,c]),j=Object(F.a)();return n.a.createElement("div",{className:"NewChat step-1"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:r,ariaLabel:"Return to Chat List"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,j("GroupAddMembers"))),n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(en,{itemIds:f,selectedIds:t,filterValue:d,filterPlaceholder:j("SendMessageTo"),searchInputId:"new-group-picker-search",isLoading:h,onSelectedIdsChange:a,onFilterChange:E}),n.a.createElement(xt,{isShown:Boolean(t.length),onClick:O,ariaLabel:e?"Continue To Channel Info":"Continue To Group Info"},n.a.createElement("i",{className:"icon-arrow-right"}))))}));var dn=Object(n.h)(Object(c.h)(e=>{const{progress:t,error:a}=e.chatCreation||{};return{creationProgress:t,creationError:a}},(e,t)=>Object(u.l)(t,["createGroupChat","createChannel"]))(({isChannel:e,memberIds:t,onReset:a,creationProgress:c,creationError:r,createGroupChat:l,createChannel:o})=>{const i=Object(F.a)(),[d,m]=Object(n.r)(""),[u,h]=Object(n.r)(""),[b,p]=Object(n.r)(),[g,v]=Object(n.r)(),E=c===s.a.InProgress,f=Object(n.m)(e=>{const{value:t}=e.currentTarget,a=t.replace(/^\s+/,"");m(a),a!==t&&(e.currentTarget.value=a)},[]),O=Object(n.m)(e=>{h(e.currentTarget.value)},[]),j=Object(n.m)(()=>{d.length?t.length>199?v("Sorry, creating supergroups is not yet supported"):l({title:d,photo:b,memberIds:t}):v("Chat title can't be empty")},[d,t,l,b,"Chat title can't be empty","Sorry, creating supergroups is not yet supported"]),C=Object(n.m)(()=>{d.length?o({title:d,about:u,photo:b,memberIds:t}):v("Channel title can't be empty")},[d,o,u,b,t,"Channel title can't be empty"]);Object(n.n)(()=>{c===s.a.Complete&&a(!0)},[c,a]);const y=r||("Chat title can't be empty"!==g&&"Channel title can't be empty"!==g?g:void 0);return n.a.createElement("div",{className:"NewChat"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>a(),ariaLabel:"Return to member selection"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,i(e?"NewChannel":"NewGroup"))),n.a.createElement("div",{className:"NewChat-inner step-2"},n.a.createElement(Dt.a,{onChange:p,title:i("AddPhoto")}),n.a.createElement(pe.a,{value:d,onChange:f,label:i(e?"EnterChannelName":"GroupName"),error:"Chat title can't be empty"===g||"Channel title can't be empty"===g?g:void 0}),e&&n.a.createElement(n.a.Fragment,null,n.a.createElement(pe.a,{value:u,onChange:O,label:i("DescriptionOptionalPlaceholder")}),n.a.createElement("p",{className:"note"},i("DescriptionInfo"))),y&&n.a.createElement("p",{className:"error"},y),n.a.createElement("h3",{className:"chat-members-heading"},i("GroupInfo.ParticipantCount",t.length,"i")),n.a.createElement("div",{className:"chat-members-list custom-scroll"},t.map(e=>n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:e}))))),n.a.createElement(xt,{isShown:0!==d.length,onClick:e?C:j,disabled:E,ariaLabel:e?i("ChannelIntro.CreateChannel"):"Create Group"},E?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-arrow-right"})))}));a(269);const mn=Object.keys(s.d).length/2;var un=Object(n.h)(({isChannel:e=!1,content:t,onContentChange:a,onReset:c})=>{const[r,l]=Object(n.r)([]),i=Object(n.m)(()=>{a(e?s.d.NewChannelStep2:s.d.NewGroupStep2)},[e,a]);return n.a.createElement(T.a,{id:"NewChat",name:o.f?"slide-layers":"push-slide",renderCount:mn,activeKey:t},()=>{switch(t){case s.d.NewChannelStep1:case s.d.NewGroupStep1:return n.a.createElement(on,{isChannel:e,selectedMemberIds:r,onSelectedMemberIdsChange:l,onNextStep:i,onReset:c});case s.d.NewChannelStep2:case s.d.NewGroupStep2:return n.a.createElement(dn,{isChannel:e,memberIds:r,onReset:c});default:return}})}),hn=a(178);a(270);var bn=Object(n.h)(({onReset:e})=>{const t=Object(F.a)();return n.a.createElement("div",{className:"ArchivedChats"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:e,ariaLabel:"Return to chat list"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,t("ArchivedChats"))),n.a.createElement(hn.a,{folderType:"archived",noChatsText:"Archive is empty."}))});const pn={Down:!0,ArrowDown:!0,Up:!0,ArrowUp:!0,Left:!0,ArrowLeft:!0,Right:!0,ArrowRight:!0," ":!0,PageUp:!0,PageDown:!0,End:!0,Home:!0,Tab:!0},gn=e=>{e.preventDefault()};function vn(e){pn[e.key]&&gn(e)}function En(){document.addEventListener("wheel",gn,{passive:!1}),window.ontouchmove=gn,document.onkeydown=vn}function fn(){document.removeEventListener("wheel",gn),window.ontouchmove=null,document.onkeydown=null}var On=a(48),jn=a(143);function Cn(e,t){return e?"Copy Selected Text":t?"Copy Text":"Copy"}var yn=a(163),kn=a(47);a(271);var Nn=({isOpen:e,message:t,anchor:a,canSendNow:c,canReschedule:s,canReply:l,canEdit:o,canPin:i,canUnpin:d,canDelete:u,canForward:h,canFaveSticker:b,canUnfaveSticker:p,canCopy:g,canCopyLink:v,canSelect:E,onReply:f,onEdit:O,onPin:C,onUnpin:y,onForward:k,onDelete:N,onFaveSticker:I,onUnfaveSticker:S,onSelect:w,onSend:P,onReschedule:M,onClose:L,onCloseAnimationEnd:A,onCopyLink:T})=>{Object(n.n)(()=>{Object(j.b)(200)},[e]);const B=function(e,t,a){const n=[],c=Object(m.N)(e),s=Object(m.G)(e),l=Object(m.D)(e,"inline"),o=s&&l&&jn.a,i=window.getSelection();if(o&&n.push({label:"Copy Media",handler:()=>{On.b(l,r.ApiMediaFormat.BlobUrl).then(jn.b),t&&t()}}),c){const e=Boolean(i&&i.anchorNode&&i.anchorNode.parentNode&&i.anchorNode.parentNode.closest(".Message .content-inner")&&""!==i.toString().replace(/(?:\r\n|\r|\n)/g,""));n.push({label:Cn(e,o),handler:()=>{const a=e&&i?i.toString():c;Object(jn.c)(a),t&&t()}})}return a&&n.push({label:"CopyMessageLink",handler:()=>{a(),t&&t()}}),n}(t,L,v?T:void 0),D=Object(n.m)(()=>document.querySelector(`.active > .MessageList div[data-message-id="${t.id}"]`),[t.id]),x=Object(n.m)(()=>document.querySelector(".active > .MessageList"),[]),U=Object(n.m)(()=>document.querySelector(".MessageContextMenu .bubble"),[]),{positionX:R,positionY:G,style:z}=Object(yn.a)(a,D,x,U,10,document.querySelector(".MiddleHeader").offsetHeight),$=Object(F.a)();return n.a.createElement(kn.a,{isOpen:e,positionX:R,positionY:G,style:z,className:"MessageContextMenu fluid",onClose:L,onCloseAnimationEnd:A},c&&n.a.createElement(q.a,{icon:"send-outline",onClick:P},$("MessageScheduleSend")),s&&n.a.createElement(q.a,{icon:"schedule",onClick:M},$("MessageScheduleEditTime")),l&&n.a.createElement(q.a,{icon:"reply",onClick:f},$("Reply")),o&&n.a.createElement(q.a,{icon:"edit",onClick:O},$("Edit")),b&&n.a.createElement(q.a,{icon:"favorite",onClick:I},$("AddToFavorites")),p&&n.a.createElement(q.a,{icon:"favorite",onClick:S},$("Stickers.RemoveFromFavorites")),g&&B.map(e=>n.a.createElement(q.a,{key:e.label,icon:"copy",onClick:e.handler},$(e.label))),i&&n.a.createElement(q.a,{icon:"pin",onClick:C},$("DialogPin")),d&&n.a.createElement(q.a,{icon:"unpin",onClick:y},$("DialogUnpin")),h&&n.a.createElement(q.a,{icon:"forward",onClick:k},$("Forward")),E&&n.a.createElement(q.a,{icon:"select",onClick:w},$("Common.Select")),u&&n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:N},$("Delete")))};var In=Object(n.h)(Object(c.h)((e,{message:t,messageListType:a})=>{const{threadId:n}=Object(d.y)(e)||{},{noOptions:c,canReply:r,canPin:s,canUnpin:l,canDelete:o,canEdit:i,canForward:m,canFaveSticker:u,canUnfaveSticker:h,canCopy:b,canCopyLink:p,canSelect:g}=n&&Object(d.b)(e,t,n)||{},v="pinned"===a,E="scheduled"===a;return{noOptions:c,canSendNow:E,canReschedule:E,canReply:!v&&!E&&r,canPin:!E&&s,canUnpin:!E&&l,canDelete:o,canEdit:!v&&i,canForward:!E&&m,canFaveSticker:!E&&u,canUnfaveSticker:!E&&h,canCopy:b,canCopyLink:!E&&p,canSelect:g}},(e,t)=>Object(u.l)(t,["setReplyingToId","setEditingId","pinMessage","openForwardMenu","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink"]))(({isOpen:e,messageListType:t,message:a,album:c,anchor:r,onClose:s,onCloseAnimationEnd:l,noOptions:o,canSendNow:i,canReschedule:d,canReply:m,canPin:u,canUnpin:h,canDelete:b,canEdit:p,canForward:g,canFaveSticker:v,canUnfaveSticker:E,canCopy:f,canCopyLink:O,canSelect:j,setReplyingToId:C,setEditingId:y,pinMessage:k,openForwardMenu:N,faveSticker:I,unfaveSticker:S,toggleMessageSelection:w,sendScheduledMessages:P,rescheduleMessage:M,loadMessageLink:F})=>{const{transitionClassNames:L}=Object(W.a)(e,l,void 0,!1),[A,T]=Object(n.r)(!0),[B,x]=Object(n.r)(!1),[U,R]=Object(n.r)(!1),[G,z,q]=Object(Ae.a)(),$=Object(n.m)(()=>{T(!1),x(!0)},[]),H=Object(n.m)(()=>{T(!1),s()},[s]),V=Object(n.m)(()=>{x(!1),s()},[s]),Y=Object(n.m)(()=>{R(!1),s()},[s]),K=Object(n.m)(()=>{q(),s()},[q,s]),Q=Object(n.m)(()=>{C({messageId:a.id}),H()},[C,a.id,H]),Z=Object(n.m)(()=>{y({messageId:a.id}),H()},[y,a.id,H]),X=Object(n.m)(()=>{T(!1),R(!0)},[]),_=Object(n.m)(()=>{k({messageId:a.id,isUnpin:!0}),H()},[k,a.id,H]),J=Object(n.m)(()=>{if(H(),c&&c.messages){const e=c.messages.map(({id:e})=>e);N({fromChatId:a.chatId,messageIds:e})}else N({fromChatId:a.chatId,messageIds:[a.id]})},[N,a,H,c]),ee=Object(n.m)(()=>{H(),I({sticker:a.content.sticker})},[H,a.content.sticker,I]),te=Object(n.m)(()=>{H(),S({sticker:a.content.sticker})},[H,a.content.sticker,S]),ae=Object(n.m)(()=>{const e=c&&c.messages?{messageId:a.id,childMessageIds:c.messages.map(({id:e})=>e),withShift:!1}:{messageId:a.id,withShift:!1};w(e),H()},[H,a.id,w,c]),ne=Object(n.m)(()=>{P({chatId:a.chatId,id:a.id}),H()},[H,a.chatId,a.id,P]),ce=Object(n.m)(()=>{T(!1),z()},[z]),re=Object(n.m)(e=>{M({chatId:a.chatId,messageId:a.id,scheduledAt:Math.round(e.getTime()/1e3)})},[a.chatId,a.id,M]),se=Object(n.m)(()=>{F({messageId:a.id,chatId:a.chatId}),H()},[H,F,a.chatId,a.id]);if(Object(n.n)(()=>(En(),fn),[]),o)return void H();const le=new Date;return le.setFullYear(le.getFullYear()+1),n.a.createElement("div",{className:["ContextMenuContainer",L].join(" ")},n.a.createElement(Nn,{message:a,isOpen:A,anchor:r,canSendNow:i,canReschedule:d,canReply:m,canDelete:b,canPin:u,canUnpin:h,canEdit:p,canForward:g,canFaveSticker:v,canUnfaveSticker:E,canCopy:f,canCopyLink:O,canSelect:j,onReply:Q,onEdit:Z,onPin:X,onUnpin:_,onForward:J,onDelete:$,onFaveSticker:ee,onUnfaveSticker:te,onSelect:ae,onSend:ne,onReschedule:ce,onClose:H,onCopyLink:se}),n.a.createElement(Me,{isOpen:B,isSchedule:"scheduled"===t,onClose:V,album:c,message:a}),n.a.createElement(Fe,{isOpen:U,messageId:a.id,chatId:a.chatId,onClose:Y}),n.a.createElement(Pe,{isOpen:G,withTimePicker:!0,selectedAt:1e3*a.date,maxAt:Object(D.k)(le),isFutureMode:!0,onClose:K,onSubmit:re}))}));a(272);var Sn=Object(n.h)(Object(c.h)((e,{fromSticker:t})=>({stickerSet:Object(d.ub)(e,t.stickerSetId)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet","sendMessage"]))(({isOpen:e,fromSticker:t,stickerSet:a,onClose:c,loadStickers:r,toggleStickerSet:s,sendMessage:o})=>{const i=Object(n.q)(null),{observe:d}=Object(aa.a)({rootRef:i,throttleMs:200,isDisabled:!e});Object(n.n)(()=>{if(e){const{stickerSetId:e,stickerSetAccessHash:a}=t;r({stickerSetId:e,stickerSetAccessHash:a})}},[e,t,r]);const m=Object(n.m)(e=>{e={...e,isPreloadedGlobally:!0},o({sticker:e}),c()},[c,o]),u=Object(n.m)(()=>{s({stickerSetId:t.stickerSetId}),c()},[t.stickerSetId,c,s]);return n.a.createElement(be.a,{className:"StickerSetModal",isOpen:e,onClose:c,hasCloseButton:!0,title:a?a.title:"Sticker Set"},a&&a.stickers?n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{ref:i,className:"stickers custom-scroll"},a.stickers.map(e=>n.a.createElement(ia,{sticker:e,size:l.vb,observeIntersection:d,onClick:m,clickArg:e}))),n.a.createElement("div",{className:"button-wrapper"},n.a.createElement(B.a,{size:"smaller",fluid:!0,color:a.installedDate?"danger":"primary",onClick:u},`${a.installedDate?"Remove":"Add"} ${a.count} stickers`))):n.a.createElement(he.a,null))})),wn=a(113);a(273);var Pn=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);return!a||a.isRestricted?{}:{chat:a,isMuted:a.isMuted,isPrivate:Object(m.kb)(a.id),canDeleteChat:Object(m.d)(a)}},(e,t)=>Object(u.l)(t,["updateChatMutedState","enterMessageSelectMode"]))(({chatId:e,isOpen:t,anchor:a,isChannel:c,canSubscribe:r,canSearch:s,canMute:l,canSelect:i,canLeave:d,chat:m,isPrivate:u,isMuted:h,canDeleteChat:b,onSubscribeChannel:p,onSearchClick:g,onClose:v,onCloseAnimationEnd:E,updateChatMutedState:f,enterMessageSelectMode:O})=>{const[j,C]=Object(n.r)(!0),[y,k]=Object(n.r)(!1),{x:N,y:I}=a;Object(W.a)(t,E,void 0,!1);const S=Object(n.m)(()=>{C(!1),k(!0)},[]),w=Object(n.m)(()=>{C(!1),v()},[v]),P=Object(n.m)(()=>{k(!1),v()},[v]),M=Object(n.m)(()=>{f({chatId:e,isMuted:!h}),w()},[e,w,h,f]),L=Object(n.m)(()=>{p(),w()},[w,p]),A=Object(n.m)(()=>{g(),w()},[w,g]),T=Object(n.m)(()=>{O(),w()},[w,O]);Object(n.n)(()=>(En(),fn),[]);const B=Object(F.a)();return n.a.createElement(wn.a,null,n.a.createElement("div",{className:"HeaderMenuContainer"},n.a.createElement(kn.a,{isOpen:j,positionX:"right",style:`left: ${N}px;top: ${I}px;`,onClose:w},o.f&&r&&n.a.createElement(q.a,{icon:c?"channel":"group",onClick:L},B(c?"Subscribe":"Join Group")),o.f&&s&&n.a.createElement(q.a,{icon:"search",onClick:A},B("Search")),l&&n.a.createElement(q.a,{icon:h?"unmute":"mute",onClick:M},B(h?"ChatsUnmute":"ChatsMute")),i&&n.a.createElement(q.a,{icon:"select",onClick:T},B("ReportSelectMessages")),d&&n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:S},B(u?"Delete":b?"Delete and Leave":"Leave"))),m&&n.a.createElement(Ge.a,{isOpen:y,onClose:P,chat:m})))})),Mn=a(144);a(274);const Fn=Object(V.a)(e=>e(),200,!1);var Ln=Object(n.h)(Object(c.h)(e=>{const t=Object(d.r)(e);if(!t)return{};const{query:a,results:n}=Object(d.A)(e)||{},{totalCount:c,foundIds:r}=n||{};return{chat:t,query:a,totalCount:c,foundIds:r}},(e,t)=>Object(u.l)(t,["setLocalTextSearchQuery","searchTextMessagesLocal","focusMessage","closeLocalTextSearch","searchMessagesByDate"]))(({isActive:e,chat:t,query:a,totalCount:c,foundIds:r,setLocalTextSearchQuery:s,searchTextMessagesLocal:l,focusMessage:o,closeLocalTextSearch:i,searchMessagesByDate:d})=>{const m=Object(n.q)(null),[u,h]=Object(n.r)(0),[b,p,g]=Object(Ae.a)();Object(n.n)(()=>{const{visualViewport:e}=window;if(!e)return;const t=document.getElementById("Main"),a=()=>{const{activeElement:a}=document;if(a&&a===m.current){const{pageTop:a,height:n}=e;t.style.transform=`translateY(${a}px)`,t.style.height=n+"px",document.documentElement.scrollTop=a}else t.style.transform="",t.style.height=""};return e.addEventListener("resize",a),()=>{e.removeEventListener("resize",a)}},[]),Object(n.n)(()=>{t&&r&&r.length?(o({chatId:t.id,messageId:r[r.length-1]}),h(0)):h(-1)},[t,o,r]),Object(n.n)(()=>{Array.from(document.querySelectorAll("input")).forEach(t=>{t.disabled=Boolean(e&&t!==m.current)}),Array.from(document.querySelectorAll("div[contenteditable]")).forEach(t=>{t.contentEditable=e?"false":"true"})},[e]),Object(n.n)(()=>{e||m.current.blur()},[e]),Object(n.o)(()=>{document.querySelector("#MobileSearch input").blur()},[b]);const v=Object(n.m)(e=>{s({query:e}),e.length&&Fn(l)},[l,s]),E=Object(n.m)(e=>{d({timestamp:e.valueOf()/1e3}),g()},[g,d]),f=Object(n.m)(()=>{if(t&&r){const e=u+1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),O=Object(n.m)(()=>{if(t&&r){const e=u-1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),j=Object(F.a)();return n.a.createElement("div",{id:"MobileSearch",className:e?"active":""},n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{size:"smaller",round:!0,color:"translucent",onClick:i},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement(Mn.a,{ref:m,value:a,onChange:v})),n.a.createElement("div",{className:"footer"},n.a.createElement("div",{className:"counter"},a?r&&r.length?`${u+1} of ${c}`:r&&!r.length?"No results":"":n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:p,ariaLabel:"Search messages by date"},n.a.createElement("i",{className:"icon-calendar"}))),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:f,disabled:!r||!r.length||u===r.length-1},n.a.createElement("i",{className:"icon-up"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:O,disabled:!r||!r.length||0===u},n.a.createElement("i",{className:"icon-down"}))),n.a.createElement(Pe,{isOpen:b,isPastMode:!0,submitButtonLabel:j("JumpToDate"),onClose:g,onSubmit:E}))})),An=a(53),Tn=a(180),Bn=a(168),Dn=a(172);var xn=function(e,t){const a=e.scrollTop,n=a+e.offsetHeight,c=t.offsetTop,r=c+t.offsetHeight;return c>a&&r{const l=Object(n.q)(null),{shouldRender:o,transitionClassNames:i}=Object(W.a)(e,void 0,void 0,!1),d=Object(n.m)(e=>{if(!s)return-1;const t=s.length;return Object(Rn.a)(t,e)},[s]),[m,u]=Object(n.r)(-1),h=Object(n.m)((e,t)=>{t.preventDefault(),u(t=>d(t+e))},[u,d]),b=Object(n.m)((e,t=!1)=>{const a=r&&r[e];a&&c(a,t)},[r,c]),p=Object(n.m)(e=>{if(s&&s.length&&m>-1){const t=s[m];t&&(e.preventDefault(),b(t.userId,!0))}},[s,m,b]);Object(n.n)(()=>e?Object(Te.a)({onEsc:a,onUp:e=>h(-1,e),onDown:e=>h(1,e),onEnter:p,onTab:p}):void 0,[e,a,h,p]),Object(n.n)(()=>{s&&!s.length&&a()},[s,a]),Object(n.n)(()=>{u(0)},[t]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a||e<0)return;const{visibleIndexes:n,allElements:c}=function(e,t,a=0,n=!1,c=!1){const r=e.scrollTop,s=r+e.offsetHeight,l="string"==typeof t?e.querySelectorAll(t):t,{length:o}=l,i=[];let d=!1;for(let e=0;e=r-a&&m<=s+a:o<=s+a&&m>=r-a)i.push(e),d=!0;else if(d&&!n)break}return{allElements:l,visibleIndexes:i}}(a,".chat-item-clickable",8,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!xn(a,c[r])){const t=e>n[n.length-1]?"start":"end";Object(Un.a)(a,c[e],t,10)}}(m,l)},[m]);const g=Object(O.a)(s&&s.length?s:void 0,o),v=s&&!s.length?g:s;if(!o||v&&!v.length)return;const E=Object(ce.a)("MentionMenu custom-scroll",i);return n.a.createElement("div",{className:E,ref:l},v&&v.map(({userId:e},t)=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable scroll-item",onClick:()=>b(e),focus:m===t},n.a.createElement(Ee.a,{userId:e,avatarSize:"small",withUsername:!0}))))});a(276);var zn=Object(n.h)(({attachments:e,caption:t,canSuggestMembers:a,groupChatMembers:c,currentUserId:r,usersById:s,onCaptionUpdate:o,onSend:i,onClear:d})=>{const m=Object(O.a)(e),u=e.length?e:m,h=Boolean(e.length),{isMentionMenuOpen:p,mentionFilter:g,closeMentionMenu:v,insertMention:E,mentionFilteredMembers:f}=Object(Tn.a)(a&&h,t,o,l.v,c,r,s);Object(n.n)(()=>h?Object(b.a)(d):void 0,[h,d]);const j=Object(n.m)(()=>{h&&i()},[h,i]),C=Object(F.a)();if(!u)return;const y=u.every(e=>e.mimeType.startsWith("image/")),k=u.every(e=>e.mimeType.startsWith("video/"));let N="";N=y?1===u.length?"Send Photo":`Send ${u.length} Photos`:k?1===u.length?"Send Video":`Send ${u.length} Videos`:1===u.length?"Send File":`Send ${u.length} Files`;const I=u.every(e=>e.quick);return n.a.createElement(be.a,{isOpen:h,onClose:d,header:function(){if(u)return n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel attachments",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},N),n.a.createElement(B.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:j},C("Send")))}(),className:"AttachmentModal"},I?n.a.createElement("div",{className:"media-wrapper custom-scroll"},u.map(e=>e.mimeType.startsWith("image/")?n.a.createElement("img",{src:e.blobUrl,alt:""}):n.a.createElement("video",{src:e.blobUrl,autoPlay:!0,muted:!0,loop:!0}))):n.a.createElement("div",{className:"document-wrapper custom-scroll"},u.map(e=>n.a.createElement(Bn.a,{name:e.filename,extension:Object(An.d)(e.filename,e.mimeType),previewData:e.previewBlobUrl,size:e.size,smaller:!0}))),n.a.createElement("div",{className:"attachment-caption-wrapper"},n.a.createElement(Gn,{isOpen:p,onClose:v,filter:g,onInsertUserName:E,filteredChatMembers:f,usersById:s}),n.a.createElement(Dn.a,{id:"caption-input-text",html:t,editableInputId:l.v,placeholder:C("Caption"),onUpdate:o,onSend:i,shouldSetFocus:h})))}),qn=a(125);a(277);var $n=Object(n.h)(({isOpen:e,onSend:t,onClear:a})=>{const c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(null),[l,o]=Object(n.r)(""),[i,d]=Object(n.r)([""]),[m,u]=Object(n.r)(!0),[h,p]=Object(n.r)(!1),[g,v]=Object(n.r)(!1),[E,f]=Object(n.r)(),[O,j]=Object(n.r)(),[C,y]=Object(n.r)(!1),k=Object(n.m)(t=>{e&&t.current&&t.current.focus()},[e]);Object(n.n)(()=>e?Object(b.a)(a):void 0,[e,a]),Object(n.n)(()=>{e||(o(""),d([""]),u(!0),p(!1),v(!1),f(""),j(""),y(!1))},[e]),Object(n.n)(()=>k(c),[k,e]),Object(n.o)(()=>{const e=s.current;e&&E!==e.innerHTML&&(e.innerHTML=E)},[E]);const N=Object(n.m)((e=[])=>{d([...e,""]),requestAnimationFrame(()=>{const e=r.current;e&&(e.classList.toggle("overflown",e.scrollHeight>320),e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))})},[]),I=Object(n.m)(()=>{if(y(!1),!e)return;const a=l.trim().substring(0,255),n=i.map(e=>e.trim().substring(0,100)).filter(e=>e.length);if(!a||n.length<2)return o(a),n.length?n.length<2?N(n):d(n):N(),void y(!0);if(g&&(!O||!n[Number(O)]))return void y(!0);const c={summary:{question:a,answers:n.map((e,t)=>({text:e.trim(),option:String(t),...String(t)===O&&{correct:!0}})),...!m&&{isPublic:!0},...h&&{multipleChoice:!0},...g&&{quiz:!0}}};if(g){const{text:e,entities:t}=E&&Object(qn.a)(E.substring(0,200))||{};c.quiz={correctAnswers:[O],...e&&{solution:e},...t&&{solutionEntities:t}}}t(c)},[e,l,i,g,O,m,h,t,N,E]),S=Object(n.m)((e,t)=>{const a=[...i];a[e]=t,a[a.length-1].trim().length&&a.length<10?N(a):d(a)},[i,N]),w=Object(n.m)(e=>{const t=[...i];t.splice(e,1),d(t),requestAnimationFrame(()=>{r.current&&r.current.classList.toggle("overflown",r.current.scrollHeight>320)})},[i]),P=Object(n.m)(e=>{j(e)},[j]),M=Object(n.m)(e=>{u(e.target.checked)},[]),L=Object(n.m)(e=>{p(e.target.checked)},[]),A=Object(n.m)(e=>{v(e.target.checked)},[]),T=Object(n.m)(e=>{13===e.keyCode&&I()},[I]),D=Object(n.m)(()=>{if(C&&!l.trim().length)return"Please enter the question"},[C,l]),x=Object(n.m)(e=>{const t=i.map(e=>e.trim()).filter(e=>e.length);if(C&&t.length<2&&!i[e].trim().length)return"Please enter at least two options"},[C,i]),U=Object(F.a)();function R(){return i.map((e,t)=>n.a.createElement("div",{className:"option-wrapper"},n.a.createElement(pe.a,{label:t!==i.length-1||10===i.length?"Option "+(t+1):"Add an Option",error:x(t),value:e,onChange:e=>S(t,e.currentTarget.value),onKeyPress:T}),t!==i.length-1&&n.a.createElement(B.a,{className:"option-remove-button",round:!0,color:"translucent",size:"smaller",ariaLabel:"Remove option",onClick:()=>w(t)},n.a.createElement("i",{className:"icon-close"}))))}return n.a.createElement(be.a,{isOpen:e,onClose:a,header:n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel poll creation",onClick:a},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},U("NewPoll")),n.a.createElement(B.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:I},U("Create"))),className:"PollModal"},n.a.createElement(pe.a,{ref:c,label:U("AskAQuestion"),value:l,error:D(),onChange:e=>o(e.currentTarget.value),onKeyPress:T}),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"options-list custom-scroll",ref:r},n.a.createElement("h3",{className:"options-header"},"Options"),C&&function(){const e=i.map(e=>e.trim()).filter(e=>e.length);return g&&(!O||!e[Number(O)])&&n.a.createElement("p",{className:"error"},"Please choose the correct answer")}(),g?n.a.createElement(ca.a,{name:"correctOption",options:R().map((e,t)=>({value:String(t),label:e,hidden:t===i.length-1})),onChange:P}):R()),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"quiz-mode"},n.a.createElement(_t.a,{label:U("PollAnonymous"),checked:m,onChange:M}),n.a.createElement(_t.a,{label:U("PollMultiple"),checked:h,disabled:g,onChange:L}),n.a.createElement(_t.a,{label:U("PollQuiz"),checked:g,disabled:h,onChange:A}),g&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"options-header"},"Solution"),n.a.createElement("div",{ref:s,className:"form-control",contentEditable:!0,onChange:e=>f(e.currentTarget.innerHTML)}),n.a.createElement("div",{className:"note"},"Users will see this comment after choosing a wrong answer, good for educational purposes."))))});let Hn;function Vn(e,t,a=250){const c=Object(n.q)(!1);Object(n.n)(()=>{Hn&&(clearTimeout(Hn),Hn=void 0),e&&!o.k&&(Hn=window.setTimeout(()=>{c.current||t()},2*a))},[e,a,t]);return[Object(n.m)(()=>{c.current=!0},[]),Object(n.m)(()=>{c.current=!1,Hn&&(clearTimeout(Hn),Hn=void 0),Hn=window.setTimeout(()=>{c.current||t()},a)},[a,t])]}var Yn=a(67),Wn=a(145);a(278);var Kn=Object(n.h)(({emoji:e,onClick:t})=>{const a=Object(n.m)(()=>{t(e.native,e.id)},[e,t]);return n.a.createElement("div",{className:"EmojiButton",onClick:a,title:e.colons},o.c?e.native:n.a.createElement("img",{src:`/img-apple-64/${e.image}.png`,alt:"",loading:"lazy"}))});var Qn=Object(n.h)(({category:e,index:t,allEmojis:a,observeIntersection:c,shouldRender:r,onEmojiSelect:s})=>{const l=Object(n.q)(null);Object(aa.c)(l,c);const{transitionClassNames:i}=Object(W.a)(r,void 0,void 0,"slow"),d=Object(F.a)(),m=o.f?Math.floor((y.a.get().width-8)/44):9,u=44*Math.ceil(e.emojis.length/m);return n.a.createElement("div",{ref:l,key:e.id,id:"emoji-category-"+t,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},d("recent"===e.id?"RecentStickers":"Emoji"+t)),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",i),style:`height: ${u}px;`},r&&e.emojis.map(e=>{const t=a[e],c="id"in t?t:t[1];return n.a.createElement(Kn,{key:c.id,emoji:c,onClick:s})})))});a(279);const Zn={recent:"icon-recent",people:"icon-smile",nature:"icon-animals",foods:"icon-eats",activity:"icon-sport",places:"icon-car",objects:"icon-lamp",symbols:"icon-language",flags:"icon-flag"},Xn=[];let _n,Jn,ec;var tc=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["recentEmojis"]),(e,t)=>Object(u.l)(t,["addRecentEmoji"]))(({className:e,onEmojiSelect:t,recentEmojis:c,addRecentEmoji:r})=>{const s=Object(n.q)(null),i=Object(n.q)(null),[d,m]=Object(n.r)(),[u,h]=Object(n.r)(),[b,p]=Object(n.r)(0),{observe:g}=Object(aa.a)({rootRef:s,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("emoji-category-"))return;const a=Number(t.replace("emoji-category-",""));Xn[a]=e.isIntersecting});const t=Xn.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&p(t[Math.floor(t.length/2)].index)});Object(qe.a)(i,!o.f),Object(n.n)(()=>{if(!d)return;const e=i.current;if(!e)return;const t=42*b-e.offsetWidth/2+21;Object(Wn.a)(e,t)},[d,b]);const v=Object(F.a)(),E=Object(n.p)(()=>{if(!d)return Ue.a;const e=[...d];return c&&c.length&&e.unshift({id:"recent",name:v("RecentStickers"),emojis:c}),e},[d,v,c]);Object(n.n)(()=>{setTimeout(()=>{const e=()=>{m(ec.categories),h(ec.emojis)};ec?e():async function(){_n||(_n=a.e(8).then(a.t.bind(null,306,3)),Jn=(await _n).default,ec=Object(Yn.b)(Jn));return _n}().then(e)},200)},[]);const f=Object(n.m)(e=>{p(e);const t=document.getElementById("emoji-category-"+e);Object(Un.a)(s.current,t,"start",50,800)},[]),O=Object(n.m)((e,a)=>{t(e),r({emoji:a})},[r,t]),j=Object(ct.a)([],l.S);const C=Object(ce.a)("EmojiPicker",e);return u&&j?n.a.createElement("div",{className:C},n.a.createElement("div",{ref:i,className:"EmojiPicker-header"},E.map((function(e,t){const a=Zn[e.id];return a&&n.a.createElement(B.a,{className:"symbol-set-button "+(t===b?"activated":""),round:!0,faded:!0,color:"translucent",onClick:()=>f(t),ariaLabel:e.name},n.a.createElement("i",{className:a}))}))),n.a.createElement("div",{ref:s,className:"EmojiPicker-main no-selection no-scrollbar"},E.map((e,t)=>n.a.createElement(Qn,{category:e,index:t,allEmojis:u,observeIntersection:g,shouldRender:b>=t-1&&b<=t+1,onEmojiSelect:O})))):n.a.createElement("div",{className:C},n.a.createElement(he.a,null))}));const ac=o.f?8:16;var nc=Object(n.h)(({stickerSet:e,loadAndPlay:t,index:a,observeIntersection:c,shouldRender:r,onStickerSelect:s,onStickerUnfave:i})=>{const d=Object(n.q)(null);Object(aa.c)(d,c);const{transitionClassNames:m}=Object(W.a)(r,void 0,void 0,"slow"),u=o.f?Math.floor((y.a.get().width-8)/(l.wb+ac)):5,h=Math.ceil(e.count/u)*(l.wb+ac);return n.a.createElement("div",{ref:d,key:e.id,id:"sticker-set-"+a,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},e.title),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",m),style:`height: ${h}px;`},r&&e.stickers&&e.stickers.map(a=>n.a.createElement(ia,{key:a.id,sticker:a,size:l.wb,observeIntersection:c,noAnimate:!t,onClick:s,clickArg:a,onUnfaveClick:"favorite"===e.id?i:void 0}))))});a(280);const cc=[];var rc=Object(n.h)(Object(c.h)(e=>{const{setsById:t,added:a,recent:n,favorite:c}=e.stickers;return{recentStickers:n.stickers,favoriteStickers:c.stickers,stickerSetsById:t,addedSetIds:a.setIds,shouldPlay:e.settings.byKey.shouldLoopStickers}},(e,t)=>Object(u.l)(t,["loadStickerSets","loadRecentStickers","loadFavoriteStickers","loadAddedStickers","addRecentSticker","unfaveSticker"]))(({className:e,loadAndPlay:t,canSendStickers:a,recentStickers:c,favoriteStickers:r,addedSetIds:s,stickerSetsById:o,shouldPlay:i,onStickerSelect:d,loadStickerSets:m,loadRecentStickers:u,loadFavoriteStickers:h,loadAddedStickers:b,addRecentSticker:p,unfaveSticker:g})=>{const v=Object(n.q)(null),E=Object(n.q)(null),[f,O]=Object(n.r)(0),{observe:j}=Object(aa.a)({rootRef:v,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("sticker-set-"))return;const a=Number(t.replace("sticker-set-",""));cc[a]=e.isIntersecting});const t=cc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&O(t[Math.floor(t.length/2)].index)}),{observe:C}=Object(aa.a)({rootRef:E}),y=Object(F.a)(),k=Boolean(s),N=Object(n.p)(()=>s?[{id:"recent",title:y("RecentStickers"),stickers:c,count:c.length},{id:"favorite",title:y("FavoriteStickers"),stickers:r,count:r.length},...s.map(e=>o[e]).filter(Boolean)]:Ue.a,[s,y,c,r,o]),I=Object(n.p)(()=>k&&0===N.filter(e=>e.stickers&&e.stickers.length).length,[N,k]);Object(n.n)(()=>{t&&(m(),u(),h())},[t,h,u,m]),Object(n.n)(()=>{s&&s.length&&b()},[s,b]),Object(qe.a)(E),Object(n.n)(()=>{if(!k)return;const e=E.current;if(!e)return;const t=52*f-(e.offsetWidth/2-26);Object(Wn.a)(e,t)},[k,f]);const S=Object(n.m)(e=>{O(e);const t=document.getElementById("sticker-set-"+e);Object(Un.a)(v.current,t,"start",void 0,500)},[]),w=Object(n.m)(e=>{d(e),p({sticker:e})},[p,d]),P=Object(n.m)(e=>{g({sticker:e})},[g]),M=Object(ct.a)([],l.nb);const L=Object(ce.a)("StickerPicker",e);return k&&M&&!I&&a?n.a.createElement("div",{className:L},n.a.createElement("div",{ref:E,className:"StickerPicker-header no-selection no-scrollbar"},N.map((function(e,t){const a=e.stickers&&e.stickers[0],c=Object(ce.a)("symbol-set-button sticker-set-button",t===f&&"activated");return"recent"===e.id||"favorite"===e.id||e.hasThumbnail||!a?n.a.createElement(B.a,{key:e.id,className:c,ariaLabel:e.title,round:!0,faded:"recent"===e.id||"favorite"===e.id,color:"translucent",onClick:()=>S(t)},"recent"===e.id?n.a.createElement("i",{className:"icon-recent"}):"favorite"===e.id?n.a.createElement("i",{className:"icon-favorite"}):e.isAnimated?n.a.createElement(la,{stickerSet:e,observeIntersection:C}):n.a.createElement(oa,{stickerSet:e,observeIntersection:C})):n.a.createElement(ia,{key:e.id,sticker:a,size:l.xb,title:e.title,className:c,observeIntersection:C,onClick:S,clickArg:t})}))),n.a.createElement("div",{ref:v,className:"StickerPicker-main no-scrollbar"},N.map((e,a)=>n.a.createElement(nc,{key:e.id,stickerSet:e,loadAndPlay:Boolean(i&&t),index:a,observeIntersection:j,shouldRender:f>=a-1&&f<=a+1,onStickerSelect:w,onStickerUnfave:P})))):n.a.createElement("div",{className:L},a?I?n.a.createElement("div",{className:"picker-disabled"},"You have no saved Stickers."):n.a.createElement(he.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending stickers is not allowed in this chat."))}));a(281);function sc(){return(sc=Object.assign||function(e){for(var t=1;t{const s=Object(n.q)(null),l=Object(n.q)(null),o="gif"+e.id,i=Object(aa.b)(s,t)&&!a,d=Object(v.a)(o+"?size=m",!i,r.ApiMediaFormat.BlobUrl),m=Object(ka.a)(e.thumbnail&&e.thumbnail.dataUri,Boolean(d)),u=d||m,h=Object(v.a)(o,!i,r.ApiMediaFormat.BlobUrl),b=Boolean(i&&h),{transitionClassNames:p}=Object(ra.a)(u||h,"slow"),{isBuffered:g,bufferingHandlers:E}=Object(K.a)(!0),f=i&&!g;Object(Z.a)(l,[b]);const O=Object(n.m)(()=>c({...e,blobUrl:h}),[c,e,h]),j=Object(ce.a)("GifButton",e.width&&e.height&&e.width({savedGifs:e.gifs.saved.gifs}),(e,t)=>Object(u.l)(t,["loadSavedGifs"]))(({className:e,loadAndPlay:t,canSendGifs:a,savedGifs:c,onGifSelect:r,loadSavedGifs:s})=>{const o=Object(n.q)(null),{observe:i}=Object(aa.a)({rootRef:o,debounceMs:300});Object(n.n)(()=>{t&&s()},[t,s]);const d=Object(ct.a)([],l.nb);return n.a.createElement("div",{ref:o,className:Object(ce.a)("GifPicker no-scrollbar",e)},a?d&&c&&c.length?c.map(e=>n.a.createElement(lc,{key:e.id,gif:e,observeIntersection:i,isDisabled:!t,onClick:r})):d&&c?n.a.createElement("div",{className:"picker-disabled"},"No saved GIFs."):n.a.createElement(he.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending GIFs is not allowed in this chat."))}));let ic;!function(e){e[e.Emoji=0]="Emoji",e[e.Stickers=1]="Stickers",e[e.GIFs=2]="GIFs"}(ic||(ic={}));const dc=Object.values(ic).filter(e=>"string"==typeof e),mc={[ic.Emoji]:"icon-smile",[ic.Stickers]:"icon-stickers",[ic.GIFs]:"icon-gifs"};var uc=Object(n.h)(({activeTab:e,onSwitchTab:t,onRemoveSymbol:a,onSearchOpen:c})=>{function r(a){return n.a.createElement(B.a,{className:"symbol-tab-button "+(e===a?"activated":""),onClick:()=>t(a),ariaLabel:dc[a],round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:mc[a]}))}const s=Object(n.m)(()=>{c(e===ic.Stickers?"stickers":"gifs")},[e,c]);return n.a.createElement("div",{className:"SymbolMenu-footer",onClick:function(e){e.stopPropagation()}},e!==ic.Emoji&&n.a.createElement(B.a,{className:"symbol-search-button",ariaLabel:e===ic.Stickers?"Search Stickers":"Search GIFs",round:!0,faded:!0,color:"translucent",onClick:s},n.a.createElement("i",{className:"icon-search"})),r(ic.Emoji),r(ic.Stickers),r(ic.GIFs),e===ic.Emoji&&n.a.createElement(B.a,{className:"symbol-delete-button",onClick:a,ariaLabel:"Remove Symbol",round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:"icon-delete-left"})))});a(283);let hc=!1;var bc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onLoad:a,onClose:c,onEmojiSelect:r,onStickerSelect:s,onGifSelect:l,onRemoveSymbol:i,onSearchOpen:d})=>{const[m,u]=Object(n.r)(0),[h,b]=Vn(e,c),{shouldRender:p,transitionClassNames:g}=Object(W.a)(e,c,!1,!1);!hc&&e&&(hc=!0),Object(n.n)(()=>{a()},[a]),Object(n.o)(()=>{if(o.f)return e&&(document.body.classList.add("enable-symbol-menu-transforms"),document.body.classList.add("is-symbol-menu-open")),()=>{e&&Object(V.b)(()=>{document.body.classList.remove("is-symbol-menu-open"),setTimeout(()=>{document.body.classList.remove("enable-symbol-menu-transforms")},350)})}},[e]);const v=Object(n.m)(e=>{c(),d(e)},[c,d]),E=Object(F.a)(),{canSendStickers:f,canSendGifs:O}=t;function j(t,a){switch(m){case ic.Emoji:return n.a.createElement(tc,{className:"picker-tab",onEmojiSelect:r});case ic.Stickers:return n.a.createElement(rc,{className:"picker-tab",loadAndPlay:!!f&&(e&&(t||a)),canSendStickers:f,onStickerSelect:s});case ic.GIFs:return n.a.createElement(oc,{className:"picker-tab",loadAndPlay:!!O&&(e&&(t||a)),canSendGifs:O,onGifSelect:l})}}const C=n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"SymbolMenu-main",onClick:function(e){e.stopPropagation()}},hc&&n.a.createElement(T.a,{name:"slide",activeKey:m,renderCount:dc.length},j)),o.f&&n.a.createElement(B.a,{round:!0,faded:!0,color:"translucent",ariaLabel:E("Close"),className:"symbol-close-button",size:"tiny",onClick:c},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(uc,{activeTab:m,onSwitchTab:u,onRemoveSymbol:i,onSearchOpen:v}));if(o.f){if(!p)return;const e=Object(ce.a)("SymbolMenu mobile-menu",g);return n.a.createElement(wn.a,null,n.a.createElement("div",{className:e},C))}return n.a.createElement(kn.a,{isOpen:e,positionX:"left",positionY:"bottom",onClose:c,className:"SymbolMenu",onCloseAnimationEnd:c,onMouseEnter:o.k?void 0:h,onMouseLeave:o.k?void 0:b,noCloseOnBackdrop:!o.k},C)});a(284);var pc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onFileSelect:a,onPollCreate:c,onClose:r})=>{const[s,i]=Vn(e,r),d=Object(n.m)((e,t)=>{const{files:n}=e.target;n&&n.length>0&&a(Array.from(n),t)},[a]),m=Object(n.m)(()=>{ga(l.k,e=>d(e,!0))},[d]),u=Object(n.m)(()=>{ga("*",e=>d(e,!1))},[d]),h=Object(F.a)(),{canAttachMedia:b,canAttachPolls:p}=t;return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:r,className:"AttachMenu fluid",onCloseAnimationEnd:r,onMouseEnter:o.k?void 0:s,onMouseLeave:o.k?void 0:i,noCloseOnBackdrop:!o.k},!b&&n.a.createElement(q.a,{className:"media-disabled",disabled:!0},"Posting media content is not allowed in this group."),b&&n.a.createElement(n.a.Fragment,null,n.a.createElement(q.a,{icon:"photo",onClick:m},h("AttachmentMenu.PhotoOrVideo")),n.a.createElement(q.a,{icon:"document",onClick:u},"Document")),p&&n.a.createElement(q.a,{icon:"poll",onClick:c},h("Poll")))});a(285);var gc=Object(n.h)(Object(c.h)(e=>{const{stickers:t}=e.stickers.forEmoji;return{stickers:t}},(e,t)=>Object(u.l)(t,["clearStickersForEmoji"]))(({isOpen:e,onStickerSelect:t,stickers:a,clearStickersForEmoji:c})=>{const r=Object(n.q)(null),{shouldRender:s,transitionClassNames:i}=Object(W.a)(e,void 0,void 0,!1),d=Object(O.a)(a,!0),m=a||d,{observe:u}=Object(aa.a)({rootRef:r,throttleMs:200});Object(n.n)(()=>e?Object(b.a)(c):void 0,[e,c]);const h=Object(ce.a)("EmojiTooltip custom-scroll",i);return n.a.createElement("div",{ref:r,className:h,onMouseEnter:o.k?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.k?void 0:()=>{document.body.classList.remove("no-select")}},s&&m?m.map(e=>n.a.createElement(ia,{key:e.id,sticker:e,size:l.wb,observeIntersection:u,onClick:t,clickArg:e})):s?n.a.createElement(he.a,null):void 0)}));a(286);var vc=Object(n.h)(Object(c.h)((e,{messageId:t})=>{const{chatId:a}=Object(d.y)(e)||{};return a?{message:Object(d.k)(e,a,t)}:{}},(e,t)=>Object(u.l)(t,["clickInlineButton"]))(({isOpen:e,message:t,onClose:a,clickInlineButton:c})=>{const[r,s]=Vn(e,a);if(t&&t.keyboardButtons)return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:a,className:"KeyboardMenu",onCloseAnimationEnd:a,onMouseEnter:o.k?void 0:r,onMouseLeave:o.k?void 0:s,noCloseOnBackdrop:!o.k},n.a.createElement("div",{className:"content"},t.keyboardButtons.map(e=>n.a.createElement("div",{className:"row"},e.map(e=>n.a.createElement(B.a,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>c({button:e})},e.text))))))}));a(287);var Ec=Object(n.h)(({isOpen:e,onSilentSend:t,onScheduleSend:a,onClose:c,onCloseAnimationEnd:r})=>{const[s,l]=Vn(e,c),i=Object(F.a)();return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",className:"CustomSendMenu",onClose:c,onCloseAnimationEnd:r,onMouseEnter:o.k?void 0:s,onMouseLeave:o.k?void 0:l,noCloseOnBackdrop:!o.k},t&&n.a.createElement(q.a,{icon:"mute",onClick:t},i("SendWithoutSound")),a&&n.a.createElement(q.a,{icon:"schedule",onClick:a},i("ScheduleMessage")))}),fc=a(126),Oc=a(154),jc=a(161);a(288);var Cc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(d.m)(e,a.id);if(!a||!n)return{};const{query:c,results:r}=Object(d.A)(e)||{},{totalCount:s,foundIds:l}=r||{};return{chat:a,messagesById:n,query:c,totalCount:s,foundIds:l}},(e,t)=>Object(u.l)(t,["searchTextMessagesLocal","focusMessage"]))(({chatId:e,threadId:t,chat:a,messagesById:r,query:s,totalCount:l,foundIds:o,searchTextMessagesLocal:i,focusMessage:h})=>{const b=Object(n.p)(()=>{if(!(s&&o&&o.length&&r))return Ue.a;const n=o.map(n=>{const s=r[n];if(!s)return;const l=s.senderId?Object(d.Db)(Object(c.e)(),s.senderId):void 0;let o;if(a&&Object(m.ib)(a))o=a;else if(s.forwardInfo){const{isChannelPost:e,fromChatId:t}=s.forwardInfo;o=e&&t?Object(d.f)(Object(c.e)(),t):void 0}else o=s.senderId?Object(d.f)(Object(c.e)(),s.senderId):void 0;return{message:s,senderUser:l,senderChat:o,onClick:()=>h({chatId:e,threadId:t,messageId:n})}}).filter(Boolean);return Object(u.k)(n,({message:e})=>e.date,"desc")},[e,t,h,o,a,r,s]);return n.a.createElement(ge.a,{className:"RightSearch custom-scroll",items:b,preloadBackwards:0,onLoadMore:i,noFastList:!0},n.a.createElement("p",{className:"helper-text"},s?1===l?"1 message found":(b.length&&(l||b.length)||"No")+" messages found":"Search messages"),b.map(({message:e,senderUser:t,senderChat:a,onClick:c})=>{const r=a?Object(m.l)(a):Object(m.Y)(t),l=Object(m.M)(e);return n.a.createElement(ve.a,{className:"chat-item-clickable search-result-message m-0",onClick:c},n.a.createElement(U.a,{chat:a,user:t}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",null,r&&Object(x.a)(r)),n.a.createElement(jc.a,{message:e})),n.a.createElement("div",{className:"subtitle"},Object(x.a)(l,["emoji","highlight"],{highlight:s}))))}))})),yc=a(103);var kc=Object(n.h)(Object(c.h)((e,{stickerSetId:t})=>({set:Object(d.ub)(e,t),shouldPlay:Object(d.tb)(e)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet"]))(({stickerSetId:e,observeIntersection:t,set:a,shouldPlay:c,loadStickers:r,toggleStickerSet:s,isSomeModalOpen:o,onModalToggle:i})=>{const d=a&&Boolean(a.installedDate),m=Boolean(a&&a.stickers),[u,h,b]=Object(Ae.a)();Object(yc.a)(()=>{i(u)},[u,i]);const p=Object(n.p)(()=>{if(!a)return[];const e=(a.covers||[]).map(({id:e})=>e),t=a.stickers?a.stickers.filter(({id:t})=>!e.includes(t)):[];return[...a.covers||[],...t].slice(0,5)},[a]);Object(n.n)(()=>{!m&&p.length<5&&r({stickerSetId:e})},[m,p.length,r,e]);const g=Object(n.m)(()=>{s({stickerSetId:e})},[s,e]);if(!a)return;const v=p.length>0;return n.a.createElement("div",{key:a.id,className:"sticker-set"},n.a.createElement("div",{className:"sticker-set-header"},n.a.createElement("div",{className:"title-wrapper"},n.a.createElement("h3",{className:"title"},a.title),n.a.createElement("p",{className:"count"},a.count," stickers")),n.a.createElement(B.a,{className:d?"is-added":void 0,color:"primary",size:"tiny",pill:!0,fluid:!0,onClick:g},d?"Added":"Add")),n.a.createElement("div",{className:"sticker-set-main"},!v&&n.a.createElement(L.a,null),v&&p.map(e=>n.a.createElement(ia,{sticker:e,size:l.yb,observeIntersection:t,noAnimate:!c||u||o,onClick:h}))),v&&n.a.createElement(ma.a,{isOpen:u,fromSticker:p[0],onClose:b}))}));a(289);const Nc=Object(V.g)(e=>e(),6e4,!0);var Ic=Object(n.h)(Object(c.h)(e=>{const t=Object(d.z)(e),{query:a,resultIds:n}=t||{},{featured:c}=e.stickers;return{query:a,featuredIds:c.setIds,resultIds:n}},(e,t)=>Object(u.l)(t,["loadFeaturedStickers"]))(({query:e,featuredIds:t,resultIds:a,loadFeaturedStickers:c})=>{const r=Object(n.q)(null),[s,l]=Object(n.r)(!1),{observe:o}=Object(aa.a)({rootRef:r,throttleMs:200});return Object(n.n)(()=>{Nc(()=>{c()})}),n.a.createElement("div",{ref:r,className:"StickerSearch custom-scroll"},function(){if(void 0!==e)return!e&&t?t.map(e=>n.a.createElement(kc,{key:e,stickerSetId:e,observeIntersection:o,isSomeModalOpen:s,onModalToggle:l})):a?a.length?a.map(e=>n.a.createElement(kc,{key:e,stickerSetId:e,observeIntersection:o,isSomeModalOpen:s,onModalToggle:l})):n.a.createElement("p",{className:"helper-text"},"Nothing found."):n.a.createElement(he.a,null)}())}));a(290);var Sc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.s)(e),{query:a,results:n}=t||{},{chatId:c}=Object(d.y)(e)||{},r=c?Object(d.f)(e,c):void 0;return{query:a,results:n,chat:r,isChatWithBot:r?Object(d.N)(e,r):void 0}},(e,t)=>Object(u.l)(t,["searchMoreGifs","sendMessage","setGifSearchQuery"]))(({query:e,results:t,chat:a,isChatWithBot:c,searchMoreGifs:r,sendMessage:s,setGifSearchQuery:l})=>{const i=Object(n.q)(null),{observe:d}=Object(aa.a)({rootRef:i,debounceMs:300}),{canSendGifs:u}=Object(m.c)(a,c),h=Object(n.m)(e=>{u&&s({gif:e}),o.k&&l({query:void 0})},[u,s,l]),b=Object(F.a)();const p=Boolean(void 0!==e&&t&&t.length);return n.a.createElement("div",{className:"GifSearch"},n.a.createElement(ge.a,{ref:i,className:Object(ce.a)("gif-container custom-scroll",p&&"grid"),items:t,itemSelector:".GifButton",preloadBackwards:96,noFastList:!0,onLoadMore:r},function(){if(void 0!==e)return t?t.length?t.map(e=>n.a.createElement(lc,{key:e.id,gif:e,observeIntersection:d,onClick:h})):n.a.createElement("p",{className:"helper-text"},b("NoGIFsFound")):n.a.createElement(he.a,null)}()))}));a(291);var wc=Object(n.h)(Object(c.h)((e,{answer:t})=>{const{voters:a,offsets:n}=e.pollResults;return{voters:a&&a[t.option],offset:n&&n[t.option]||""}},(e,t)=>Object(u.l)(t,["loadPollOptionResults","openChat","closePollResults"]))(({chat:e,message:t,answer:a,answerVote:c,totalVoters:r,voters:s,offset:l,loadPollOptionResults:o,openChat:i,closePollResults:d})=>{const m=Object(O.a)(c.votersCount),[u,h]=Object(n.r)(!0),b=Boolean(s),{option:p,text:g}=a;Object(n.n)(()=>{b&&m===c.votersCount||o({chat:e,messageId:t.id,option:p,offset:l,limit:4,shouldResetVoters:!0})},[c.votersCount,b]);const v=Object(n.m)(()=>{h(!0),o({chat:e,messageId:t.id,option:p,offset:l,limit:50})},[e,o,t.id,l,p]);Object(n.n)(()=>{h(!1)},[s]);const E=Object(n.m)(e=>{i({id:e}),d()},[d,i]);return n.a.createElement("div",{className:"PollAnswerResults"},n.a.createElement("div",{className:"poll-voters"},s?s.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable",onClick:()=>E(e)},n.a.createElement(Ee.a,{avatarSize:"tiny",userId:e,forceShowSelf:!0,noStatusOrTyping:!0}))):n.a.createElement(he.a,null),s&&function(){const e=c.votersCount-s.length;return c.votersCount>4&&e>0&&n.a.createElement(Kt,{count:e,itemName:"voter",isLoading:u,onClick:v})}()),n.a.createElement("div",{className:"answer-head"},n.a.createElement("span",{className:"answer-title"},g),n.a.createElement("span",{className:"answer-percent"},(f=c.votersCount,(j=r)>0?(f/j*100).toFixed():0),"%")));var f,j}));a(292);var Pc=Object(n.h)(Object(c.h)(e=>{const{pollResults:{chatId:t,messageId:a},lastSyncTime:n}=e;if(!t||!a)return{};return{chat:Object(d.f)(e,t),message:Object(d.k)(e,t,a),lastSyncTime:n}})(({chat:e,message:t,lastSyncTime:a})=>{if(!t||!e)return n.a.createElement(he.a,null);const{summary:c,results:r}=Object(m.H)(t);if(!r.results)return;const s=Object(u.c)(r.results,"option");return n.a.createElement("div",{className:"PollResults"},n.a.createElement("h3",{className:"poll-question"},c.question),n.a.createElement("div",{className:"poll-results-list custom-scroll"},a&&c.answers.map(a=>n.a.createElement(wc,{key:`${t.id}-${a.option}`,chat:e,message:t,answer:a,answerVote:s[a.option],totalVoters:r.totalVoters})),!a&&n.a.createElement(he.a,null)))}));a(156);var Mc=Object(n.h)(Object(c.h)((e,{userId:t})=>{const a=Object(d.Db)(e,t),n=Object(d.f)(e,t),{progress:c}=e.management;return{user:a,chat:n,progress:c}},(e,t)=>Object(u.l)(t,["updateContact","deleteUser","closeManagement","openChat","deleteHistory"]))(({userId:e,user:t,chat:a,progress:c,updateContact:r,deleteUser:l,deleteHistory:o,closeManagement:i,openChat:d})=>{const[m,u,h]=Object(Ae.a)(),[b,p]=Object(n.r)(!1),[g,v]=Object(n.r)(),E=Object(F.a)(),f=t&&t.firstName||"",O=t&&t.lastName||"",j=a?a.isMuted:void 0,[C,y]=Object(n.r)(f),[k,N]=Object(n.r)(O),[I,S]=Object(n.r)(!j);Object(n.n)(()=>{S(!j)},[j]),Object(n.n)(()=>{p(!1),h()},[h,e]),Object(n.n)(()=>{y(f),N(O)},[f,O,t]),Object(n.n)(()=>{c===s.f.Complete&&(p(!1),v(void 0),h())},[h,c]);const w=Object(n.m)(e=>{y(e.target.value),p(!0)},[]),P=Object(n.m)(e=>{N(e.target.value),p(!0)},[]),M=Object(n.m)(e=>{S(e.target.checked),p(!0)},[]),A=Object(n.m)(()=>{const t=C.trim(),a=k.trim();t.length||v("Please provide first name"),r({userId:e,isMuted:!I,firstName:t,lastName:a})},[C,k,r,e,I]),T=Object(n.m)(()=>{a.lastMessage&&o({chatId:a.id,maxId:a.lastMessage.id,shouldDeleteForAll:!1}),l({userId:e}),h(),i(),d({id:void 0})},[a.id,a.lastMessage,h,i,o,l,d,e]);if(!t)return;const B=c===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{userId:t.id,avatarSize:"jumbo",status:"original name",withFullInfo:!0}),n.a.createElement(pe.a,{id:"user-first-name",label:E("UserInfo.FirstNamePlaceholder"),onChange:w,value:C,error:"Please provide first name"===g?g:void 0}),n.a.createElement(pe.a,{id:"user-last-name",label:E("UserInfo.LastNamePlaceholder"),onChange:P,value:k}),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(_t.a,{checked:I,label:E("Notifications"),subLabel:E(I?"UserInfo.NotificationsEnabled":"UserInfo.NotificationsDisabled"),onChange:M}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:u},E("DeleteContact")))),n.a.createElement(xt,{isShown:b,onClick:A,disabled:B,ariaLabel:E("Save")},B?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:m,onClose:h,text:E("AreYouSureDeleteContact"),confirmLabel:E("DeleteContact"),confirmHandler:T,confirmIsDestructive:!0}))}));var Fc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management,c=Boolean(a.fullInfo&&a.fullInfo.linkedChatId);return{chat:a,progress:n,isBasicGroup:Object(m.hb)(a),hasLinkedChannel:c,canChangeInfo:Object(m.q)(a,"changeInfo"),canBanUsers:Object(m.q)(a,"banUsers")}},(e,t)=>Object(u.l)(t,["togglePreHistoryHidden","updateChat","closeManagement","deleteHistory","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isBasicGroup:c,hasLinkedChannel:l,canChangeInfo:o,canBanUsers:i,onScreenSelect:d,togglePreHistoryHidden:u,updateChat:h,deleteHistory:b,leaveChannel:p,deleteChannel:g,closeManagement:E,openChat:f})=>{const[O,j,C]=Object(Ae.a)(),y=t.title,k=t.fullInfo&&t.fullInfo.about||"",[N,I]=Object(n.r)(!1),[S,w]=Object(n.r)(y),[P,M]=Object(n.r)(k),[A,T]=Object(n.r)(),[B,D]=Object(n.r)(),U=Object(m.f)(t),R=Object(v.a)(U,!1,r.ApiMediaFormat.BlobUrl),G=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(I(!1),D(void 0))},[a]);const z=Object(n.m)(()=>{d(s.g.ChatPrivacyType)},[d]),q=Object(n.m)(()=>{d(s.g.Discussion)},[d]),$=Object(n.m)(()=>{d(s.g.GroupPermissions)},[d]),H=Object(n.m)(()=>{d(s.g.ChatAdministrators)},[d]),V=Object(n.m)(e=>{T(e),I(!0)},[]),Y=Object(n.m)(e=>{w(e.target.value),I(!0)},[]),W=Object(n.m)(e=>{M(e.target.value),I(!0)},[]),K=Object(n.m)(()=>{const t=S.trim(),a=P.trim();t.length?h({chatId:e,title:t,about:a,photo:A}):D("Group title can't be empty")},[P,e,A,S,h]),Q=Object(n.m)(()=>{d(s.g.GroupMembers)},[d]),Z=Object(n.m)(()=>{if(!t.fullInfo)return;const{isPreHistoryHidden:e}=t.fullInfo;u({chatId:t.id,isEnabled:!e})},[t,u]),X=Object(n.p)(()=>{if(!t.defaultBannedRights)return 0;let e=["sendMessages","sendMedia","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages"].filter(e=>!t.defaultBannedRights[e]).length;const{sendStickers:a,sendGifs:n}=t.defaultBannedRights;return a||n||(e+=1),e},[t]),_=t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,J=Object(n.m)(()=>{c?b({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!1}):t.isCreator?g({chatId:t.id}):p({chatId:t.id}),C(),E(),f({id:void 0})},[c,t.isCreator,t.id,t.lastMessage,C,E,b,p,g,f]);if(t.isRestricted)return;const ee=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:R,onChange:V,disabled:!o}),n.a.createElement(pe.a,{id:"group-title",label:G("GroupName"),onChange:Y,value:S,error:"Group title can't be empty"===B?B:void 0,disabled:!o}),n.a.createElement(pe.a,{id:"group-about",className:"mb-2",label:G("DescriptionPlaceholder"),onChange:W,value:P,disabled:!o}),t.isCreator&&n.a.createElement(ve.a,{icon:"lock",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},G("GroupType")),n.a.createElement("span",{className:"subtitle"},t.username?G("TypePublic"):G("TypePrivate"))),l&&n.a.createElement(ve.a,{icon:"message",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},G("LinkedChannel")),n.a.createElement("span",{className:"subtitle"},G("DiscussionUnlink"))),n.a.createElement(ve.a,{icon:"permissions",multiline:!0,ripple:!0,onClick:$,disabled:!i},n.a.createElement("span",{className:"title"},G("ChannelPermissions")),n.a.createElement("span",{className:"subtitle"},X,"/",8)),n.a.createElement(ve.a,{icon:"admin",multiline:!0,ripple:!0,onClick:H},n.a.createElement("span",{className:"title"},G("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},Object(sa.a)(_)))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"group",multiline:!0,ripple:!0,onClick:Q},n.a.createElement("span",{className:"title"},G("GroupMembers")),n.a.createElement("span",{className:"subtitle"},Object(sa.a)(t.membersCount))),t.fullInfo&&n.a.createElement("div",{className:"ListItem narrow no-selection"},n.a.createElement(_t.a,{checked:!t.fullInfo.isPreHistoryHidden,label:G("ChatHistory"),onChange:Z,disabled:!i}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},G("DeleteMega")))),n.a.createElement(xt,{isShown:N,onClick:K,disabled:ee,ariaLabel:G("Save")},ee?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:O,onClose:C,textParts:Object(x.a)(c||!t.isCreator?G("AreYouSureDeleteAndExit"):G("AreYouSureDeleteThisChatWithGroup",t.title),["br","simple_markdown"]),confirmLabel:c||!t.isCreator?G("DeleteMega"):G("DeleteGroupForAll"),confirmHandler:J,confirmIsDestructive:!0}))}));var Lc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t),currentUserId:e.currentUserId}),(e,t)=>Object(u.l)(t,["updateChatDefaultBannedRights"]))(({onScreenSelect:e,onChatMemberSelect:t,chat:a,currentUserId:c,updateChatDefaultBannedRights:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(F.a)(),b=Object(n.m)(()=>{e(s.g.GroupRemovedUsers)},[e]),p=Object(n.m)(()=>{e(s.g.GroupUserPermissionsCreate)},[e]),g=Object(n.m)(a=>{t(a.userId,a.promotedByUserId===c),e(s.g.GroupUserPermissions)},[c,t,e]);Object(n.n)(()=>{o(a&&a.defaultBannedRights||{}),d(!1),setTimeout(()=>{u(!1)},250)},[a]);const v=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),E=Object(n.m)(()=>{a&&(u(!0),r({chatId:a.id,bannedRights:l}))},[a,l,r]),f=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.kickedMembers?a.fullInfo.kickedMembers.length:0,[a]),O=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.members?a.fullInfo.members.filter(({bannedRights:e})=>!!e):[],[a]),j=Object(n.m)(e=>{const{bannedRights:t}=e;if(!t||!a)return;const{defaultBannedRights:n}=a;return Object.keys(t).reduce((e,a)=>{if(!t[a]||n&&n[a]||"sendInline"===a||"viewMessages"===a||"sendGames"===a)return e;const c=function(e){switch(e){case"sendMessages":return"UserRestrictionsNoSend";case"sendMedia":return"UserRestrictionsNoSendMedia";case"sendStickers":return"UserRestrictionsNoSendStickers";case"embedLinks":return"UserRestrictionsNoEmbedLinks";case"sendPolls":return"UserRestrictionsNoSendPolls";case"changeInfo":return"UserRestrictionsNoChangeInfo";case"inviteUsers":return"UserRestrictionsInviteUsers";case"pinMessages":return"UserRestrictionsPinMessages";default:return}}(a);if(!c)return e;const r=h(c);return`${e}${e.length?", "+r:r}`},"")},[a,h]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},h("ChannelPermissionsHeader")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMessages",checked:!l.sendMessages,label:h("UserRestrictionsSend"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMedia",checked:!l.sendMedia,label:h("UserRestrictionsSendMedia"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:h("UserRestrictionsSendStickers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendPolls",checked:!l.sendPolls,label:h("UserRestrictionsSendPolls"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"embedLinks",checked:!l.embedLinks,label:h("UserRestrictionsEmbedLinks"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!l.inviteUsers,label:h("UserRestrictionsInviteUsers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!l.pinMessages,label:h("UserRestrictionsPinMessages"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!l.changeInfo,label:h("UserRestrictionsChangeInfo"),blocking:!0,onChange:v}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete-user",multiline:!0,ripple:!0,narrow:!0,onClick:b},n.a.createElement("span",{className:"title"},h("ChannelBlockedUsers")),n.a.createElement("span",{className:"subtitle"},f))),n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},h("PrivacyExceptions")),n.a.createElement(ve.a,{icon:"add-user",ripple:!0,onClick:p},h("ChannelAddException")),O.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable exceptions-member",ripple:!0,onClick:()=>g(e)},n.a.createElement(Ee.a,{userId:e.userId,status:j(e)}))))),n.a.createElement(xt,{isShown:i,onClick:E,ariaLabel:h("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var Ac=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,usersById:n}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,usersById:t,updateChatMemberBannedRights:a})=>{const c=Object(F.a)(),r=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.kickedMembers?e.fullInfo.kickedMembers:[],[e]),s=Object(n.m)(e=>{if(!e.kickedByUserId)return;const a=t[e.kickedByUserId];return a?c("UserRemovedBy",Object(m.Y)(a)):void 0},[c,t]),l=Object(n.m)(t=>{if(e)return[{title:c("Unblock"),icon:"delete",destructive:!0,handler:()=>a({chatId:e.id,userId:t.userId,bannedRights:{}})}]},[c,e,a]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("p",{className:"text-muted"},c("NoBlockedGroup2")),r.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,contextActions:l(e)},n.a.createElement(Ee.a,{userId:e.userId,status:s(e)}))))))}));var Tc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management;return{chat:a,progress:n,isSignaturesShown:Boolean(a&&a.isSignaturesShown),canChangeInfo:Object(m.q)(a,"changeInfo")}},(e,t)=>Object(u.l)(t,["toggleSignatures","updateChat","closeManagement","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isSignaturesShown:c,canChangeInfo:l,onScreenSelect:o,updateChat:i,toggleSignatures:d,closeManagement:u,leaveChannel:h,deleteChannel:b,openChat:p})=>{const g=t&&t.title||"",E=t&&t.fullInfo&&t.fullInfo.about||"",f=t&&t.fullInfo&&t.fullInfo.linkedChatId,[O,j,C]=Object(Ae.a)(),[y,k]=Object(n.r)(!1),[N,I]=Object(n.r)(g),[S,w]=Object(n.r)(E),[P,M]=Object(n.r)(),[A,T]=Object(n.r)(),B=t&&Object(m.f)(t),D=Object(v.a)(B,!1,r.ApiMediaFormat.BlobUrl),x=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(k(!1),T(void 0))},[a]);const U=t&&t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,R=Object(n.m)(()=>{o(s.g.ChatPrivacyType)},[o]),G=Object(n.m)(()=>{o(s.g.Discussion)},[o]),z=Object(n.m)(()=>{o(s.g.ChatAdministrators)},[o]),q=Object(n.m)(e=>{M(e),k(!0)},[]),$=Object(n.m)(e=>{I(e.target.value),k(!0)},[]),H=Object(n.m)(e=>{w(e.target.value),k(!0)},[]),V=Object(n.m)(()=>{const t=N.trim(),a=S.trim();t.length?i({chatId:e,title:t,about:a,photo:P}):T("Channel title can't be empty")},[S,e,P,N,i]),Y=Object(n.m)(()=>{d({chatId:e,isEnabled:!c})},[e,c,d]),W=Object(n.m)(()=>{o(s.g.ChannelSubscribers)},[o]),K=Object(n.m)(()=>{t.isCreator?b({chatId:t.id}):h({chatId:t.id}),C(),u(),p({id:void 0})},[t.isCreator,t.id,C,u,h,b,p]);if(t.isRestricted)return;const Q=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:D,onChange:q,disabled:!l}),n.a.createElement(pe.a,{id:"channel-title",label:x("EnterChannelName"),onChange:$,value:N,error:"Channel title can't be empty"===A?A:void 0,disabled:!l}),n.a.createElement(pe.a,{id:"channel-about",className:"mb-2",label:x("DescriptionPlaceholder"),onChange:H,value:S,disabled:!l}),t.isCreator&&n.a.createElement(ve.a,{icon:"lock",ripple:!0,multiline:!0,onClick:R},n.a.createElement("span",{className:"title"},x("ChannelType")),n.a.createElement("span",{className:"subtitle"},t.username?x("TypePublic"):x("TypePrivate"))),n.a.createElement(ve.a,{icon:"message",multiline:!0,ripple:!0,onClick:G,disabled:!l},n.a.createElement("span",{className:"title"},x("Discussion")),n.a.createElement("span",{className:"subtitle"},x(f?"DiscussionUnlink":"Add"))),n.a.createElement(ve.a,{icon:"admin",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},x("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},U)),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(_t.a,{checked:c,label:x("ChannelSignMessages"),onChange:Y}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"group",multiline:!0,ripple:!0,onClick:W},n.a.createElement("span",{className:"title"},x("ChannelSubscribers")),n.a.createElement("span",{className:"subtitle"},x("Subscribers",t.membersCount,"i")))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},t.isCreator?x("ChannelDelete"):x("LeaveChannel")))),n.a.createElement(xt,{isShown:y,onClick:V,disabled:Q,ariaLabel:x("Save")},Q?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:O,onClose:C,text:t.isCreator?x("ChannelDeleteAlert"):x("ChannelLeaveAlert"),confirmLabel:t.isCreator?x("ChannelDelete"):x("LeaveChannel"),confirmHandler:K,confirmIsDestructive:!0}))})),Bc=a(51);var Dc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{isUsernameAvailable:n}=Object(d.Y)(e,t);return{chat:a,isChannel:Object(m.ib)(a),progress:e.management.progress,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["checkPublicLink","updatePublicLink","updatePrivateLink"]))(({chat:e,isChannel:t,progress:a,isUsernameAvailable:c,checkPublicLink:r,updatePublicLink:l,updatePrivateLink:o})=>{const i=Boolean(e.username),d=e.fullInfo&&e.fullInfo.inviteLink,[m,u]=Object(n.r)(i?"public":"private"),[h,b]=Object(n.r)(),[p,g,v]=Object(Ae.a)(),E="public"===m&&h&&c||"private"===m&&i;Object(n.n)(()=>{m&&!d&&o()},[m,d,o]);const f=Object(n.m)(e=>{u(e)},[]),O=Object(n.m)(()=>{l({username:"public"===m?h:""})},[m,l,h]),j=Object(n.m)(()=>{v(),o()},[v,o]),C=Object(F.a)(),y=t?"Channel":"Mega",k=t?"Channel":"Group",N=[{value:"private",label:C(y+"Private"),subLabel:C(y+"PrivateInfo")},{value:"public",label:C(y+"Public"),subLabel:C(y+"PublicInfo")}],I=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},C(k+"Type")),n.a.createElement(ca.a,{selected:m,name:"channel-type",options:N,onChange:f})),"private"===m?n.a.createElement("div",{className:"section"},d?n.a.createElement(n.a.Fragment,null,n.a.createElement(Bc.a,{url:d,className:"group-link",text:d}),n.a.createElement("p",{className:"section-info"},C(y+"PrivateLinkHelp")),n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:g},C("RevokeLink")),n.a.createElement(Lt.a,{isOpen:p,onClose:v,text:C("RevokeAlert"),confirmLabel:C("RevokeButton"),confirmHandler:j,confirmIsDestructive:!0})):n.a.createElement(he.a,null)):n.a.createElement("div",{className:"section no-border"},n.a.createElement(zt,{asLink:!0,currentUsername:e.username,isLoading:I,isUsernameAvailable:c,checkUsername:r,onChange:b}),n.a.createElement("p",{className:"section-info"},C(k+".Username.CreatePublicLinkHelp")))),n.a.createElement(xt,{isShown:E,disabled:I,ariaLabel:C("Save"),onClick:O},I?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var xc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{forDiscussionIds:n,byId:c}=e.chats;return{chat:a,chatsByIds:c,forDiscussionIds:n,linkedChat:a&&a.fullInfo&&a.fullInfo.linkedChatId?Object(d.f)(e,a.fullInfo.linkedChatId):void 0,isChannel:a&&Object(m.ib)(a)}},(e,t)=>Object(u.l)(t,["loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup"]))(({chat:e,chatId:t,chatsByIds:a,linkedChat:c,forDiscussionIds:r,isChannel:o,onScreenSelect:i,loadGroupsForDiscussion:d,linkDiscussionGroup:m,unlinkDiscussionGroup:u})=>{const[h,b]=Object(n.r)(),[p,g]=Object(n.r)(),[v,E]=Object(n.r)(!1),f=Object(n.m)(()=>E(!0),[]),[O,j,C]=Object(Ae.a)(),[y,k,N]=Object(Ae.a)(),I=Object(F.a)(),S=c&&c.id;Object(n.n)(()=>{d()},[d]),Object(n.n)(()=>{p||Object(Ht.a)("DiscussionGroups").then(g)},[p]);const w=Object(n.m)(()=>{C(),u({channelId:o?t:S}),o||i(s.g.Initial)},[C,u,o,t,S,i]),P=Object(n.m)(()=>{N(),m({channelId:t,chatId:h})},[N,m,t,h]);function M(){const e=a[h];if(e)return n.a.createElement("div",{className:"modal-header"},n.a.createElement(U.a,{size:"tiny",chat:e}),n.a.createElement("div",{className:"modal-title"},I("Channel.DiscussionGroup.LinkGroup")))}function L(){const t=a[h];if(t)return t.hasPrivateLink?Object(x.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?`,["br","simple_markdown"]):Object(x.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?\n\nAnyone from the channel will be able to see messages in this group.`,["br","simple_markdown"])}return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("div",{className:"section-icon"},p&&n.a.createElement(Vt.a,{id:"discussionGroupsDucks",size:l.qb,animationData:p,play:v,noLoop:!0,onLoad:f})),c&&n.a.createElement("div",null,n.a.createElement(ve.a,{className:"chat-item-clickable",inactive:!0},n.a.createElement(fe.a,{chatId:c.id})),n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel")),n.a.createElement(Lt.a,{isOpen:O,onClose:C,header:n.a.createElement("div",{className:"modal-header"},n.a.createElement(U.a,{size:"tiny",chat:c}),n.a.createElement("div",{className:"modal-title"},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"))),textParts:Object(x.a)(I(o?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",c.title),["br","simple_markdown"]),confirmLabel:I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"),confirmHandler:w,confirmIsDestructive:!0})),!c&&n.a.createElement("div",null,n.a.createElement("p",{className:"section-help"},I("DiscussionChannelHelp")),n.a.createElement("div",{teactFastList:!0},n.a.createElement(ve.a,{key:"create-group",icon:"group",ripple:!0,teactOrderKey:0,className:"not-implemented"},I("DiscussionCreateGroup")),r?r.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t+1,className:"chat-item-clickable scroll-item",onClick:()=>{b(e),k()}},n.a.createElement(fe.a,{chatId:e}))):n.a.createElement(Qe.a,{key:"nothing-found",teactOrderKey:0,text:"No discussion groups found"})),n.a.createElement("p",{className:"mt-4 mb-0 section-help"},I("DiscussionChannelHelp2")),n.a.createElement(Lt.a,{isOpen:y,onClose:N,header:M(),textParts:L(),confirmLabel:I("DiscussionLinkGroup"),confirmHandler:P,isButtonsInOneRow:!0})))))}));var Uc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t);return{chat:n,isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,selectedChatMemberId:t,onScreenSelect:a,updateChatMemberBannedRights:c,isFormFullyDisabled:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),[h,b,p]=Object(Ae.a)(),g=Object(F.a)(),v=Object(n.p)(()=>{if(e&&e.fullInfo&&e.fullInfo.members)return e.fullInfo.members.find(({userId:e})=>e===t)},[e,t]);Object(n.n)(()=>{e&&e.fullInfo&&t&&!v&&a(s.g.GroupPermissions)},[e,a,v,t]),Object(n.n)(()=>{o(v&&v.bannedRights||e&&e.defaultBannedRights||{}),d(!1),u(!1)},[e,v]);const E=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),f=Object(n.m)(()=>{e&&t&&(u(!0),c({chatId:e.id,userId:t,bannedRights:l}))},[e,t,l,c]),O=Object(n.m)(()=>{e&&t&&c({chatId:e.id,userId:t,bannedRights:{viewMessages:!0}})},[e,t,c]),j=Object(n.m)(t=>!!r||!(!e||!e.defaultBannedRights)&&e.defaultBannedRights[t],[e,r]);if(v)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:v.userId})),n.a.createElement("h3",{className:"section-heading mt-4"},g("UserRestrictionsCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMessages",checked:!l.sendMessages,label:g("UserRestrictionsSend"),blocking:!0,disabled:j("sendMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMedia",checked:!l.sendMedia,label:g("UserRestrictionsSendMedia"),blocking:!0,disabled:j("sendMedia"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:g("UserRestrictionsSendStickers"),blocking:!0,disabled:j("sendStickers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendPolls",checked:!l.sendPolls,label:g("UserRestrictionsSendPolls"),blocking:!0,disabled:j("sendPolls"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"embedLinks",checked:!l.embedLinks,label:g("UserRestrictionsEmbedLinks"),blocking:!0,disabled:j("embedLinks"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!l.inviteUsers,label:g("UserRestrictionsInviteUsers"),blocking:!0,disabled:j("inviteUsers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!l.pinMessages,label:g("UserRestrictionsPinMessages"),blocking:!0,disabled:j("pinMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!l.changeInfo,label:g("UserRestrictionsChangeInfo"),blocking:!0,disabled:j("changeInfo"),onChange:E}))),!r&&n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete-user",ripple:!0,destructive:!0,onClick:b},g("UserRestrictionsBlock")))),n.a.createElement(xt,{isShown:i,onClick:f,ariaLabel:g("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:h,onClose:p,text:"Are you sure you want to ban and remove this user from the group?",confirmLabel:"Remove",confirmHandler:O,confirmIsDestructive:!0}))}));var Rc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,currentUserId:e.currentUserId,isChannel:Object(m.ib)(a),usersById:n}})(({chat:e,isChannel:t,currentUserId:a,usersById:c,onScreenSelect:r,onChatMemberSelect:l})=>{const o=Object(F.a)();const i=Object(n.p)(()=>e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),d=Object(n.m)(e=>{l(e.userId,e.promotedByUserId===a),r(s.g.ChatAdminRights)},[a,l,r]),u=Object(n.m)(e=>{if(e.isOwner)return o("ChannelCreator");const t=e.promotedByUserId?c[e.promotedByUserId]:void 0;return t?o("EditAdminPromotedBy",Object(m.Y)(t)):o("ChannelAdmin")},[o,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"recent",multiline:!0,ripple:!0,onClick:function(){r(s.g.GroupRecentActions)}},n.a.createElement("span",{className:"title"},o("EventLog")),n.a.createElement("span",{className:"subtitle"},o(t?"EventLogInfoDetailChannel":"EventLogInfoDetail")))),n.a.createElement("div",{className:"section"},n.a.createElement("p",{className:"text-muted"},t?"You can add administrators to help you manage your channel.":"You can add administrators to help you manage your group."),i.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,onClick:()=>d(e)},n.a.createElement(Ee.a,{userId:e.userId,status:u(e),forceShowSelf:!0}))))))}));var Gc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t)}))(({chat:e})=>{const t=Object(F.a)(),a=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),c=Object(n.m)(e=>e.isOwner?t("ChannelCreator"):t("ChannelAdmin"),[t]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section not-implemented"},n.a.createElement("h3",{className:"section-heading"},"Actions"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogAllEvents"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewAdmins"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewMembers"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterChannelInfo"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterDeletedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterEditedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterLeavingMembers"),onChange:void 0}))),n.a.createElement("div",{className:"section not-implemented"},n.a.createElement("h3",{className:"section-heading"},"Admins"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogAllAdmins"),onChange:void 0})),a.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable picker-list-item",onClick:void 0,ripple:!0},n.a.createElement(_t.a,{label:"",checked:!0}),n.a.createElement(Ee.a,{userId:e.userId,status:c(e),forceShowSelf:!0}))))))}));var zc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t),{byId:c}=e.users,{currentUserId:r}=e;return{chat:n,usersById:c,currentUserId:r,isChannel:Object(m.ib)(n),isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatAdmin"]))(({selectedChatMemberId:e,onScreenSelect:t,chat:a,usersById:c,currentUserId:r,isChannel:l,isFormFullyDisabled:o,updateChatAdmin:i})=>{const[d,u]=Object(n.r)({}),[h,b]=Object(n.r)(!1),[p,g]=Object(n.r)(!1),[v,E,f]=Object(Ae.a)(),[O,j]=Object(n.r)(""),C=Object(F.a)(),y=Object(n.p)(()=>{if(a.fullInfo&&a.fullInfo.adminMembers)return a.fullInfo.adminMembers.find(({userId:t})=>t===e)},[a,e]);Object(n.n)(()=>{a&&a.fullInfo&&e&&!y&&t(s.g.ChatAdministrators)},[a,t,y,e]),Object(n.n)(()=>{u(y&&y.adminRights||{}),j((y&&y.customTitle||"").substr(0,16)),b(!1),g(!1)},[y]);const k=Object(n.m)(e=>{const{name:t}=e.target;u(e=>{return{...e,[t]:(a=e[t],!a||void 0)};var a}),b(!0)},[]),N=Object(n.m)(()=>{e&&(g(!0),i({chatId:a.id,userId:e,adminRights:d,customTitle:O}))},[a,e,d,O,i]),I=Object(n.m)(()=>{e&&(i({chatId:a.id,userId:e,adminRights:{}}),f())},[a.id,f,e,i]),S=Object(n.m)(e=>!Object(m.hb)(a)&&(!(!o&&a.adminRights)||!a.adminRights[e]),[a,o]),w=Object(n.p)(()=>{if(!y)return;if(y.isOwner)return C("ChannelCreator");const e=y.promotedByUserId?c[y.promotedByUserId]:void 0;return e?C("EditAdminPromotedBy",Object(m.Y)(e)):C("ChannelAdmin")},[y,c,C]),P=Object(n.m)(e=>{const{value:t}=e.target;j(t),b(!0)},[]);if(y)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:y.userId,status:w,forceShowSelf:!0})),n.a.createElement("h3",{className:"section-heading mt-4"},C("EditAdminWhatCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!!d.changeInfo,label:C(l?"EditAdminChangeChannelInfo":"EditAdminChangeGroupInfo"),blocking:!0,disabled:S("changeInfo"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"postMessages",checked:!!d.postMessages,label:C("EditAdminPostMessages"),blocking:!0,disabled:S("postMessages"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"editMessages",checked:!!d.editMessages,label:C("EditAdminEditMessages"),blocking:!0,disabled:S("editMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"deleteMessages",checked:!!d.deleteMessages,label:C(l?"EditAdminDeleteMessages":"EditAdminGroupDeleteMessages"),blocking:!0,disabled:S("deleteMessages"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"banUsers",checked:!!d.banUsers,label:C("EditAdminBanUsers"),blocking:!0,disabled:S("banUsers"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!!d.inviteUsers,label:C("EditAdminAddUsers"),blocking:!0,disabled:S("inviteUsers"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!!d.pinMessages,label:C("EditAdminPinMessages"),blocking:!0,disabled:S("pinMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"addAdmins",checked:!!d.addAdmins,label:C("EditAdminAddAdmins"),blocking:!0,disabled:S("addAdmins"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"anonymous",checked:!!d.anonymous,label:C("EditAdminSendAnonymously"),blocking:!0,disabled:S("anonymous"),onChange:k})),o&&n.a.createElement("p",{className:"section-info mb-4"},C("Channel.EditAdmin.CannotEdit")),!l&&n.a.createElement(pe.a,{id:"admin-title",label:C("EditAdminRank"),onChange:P,value:O,disabled:o,maxLength:16}),r!==e&&!o&&n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:E},C("EditAdminRemoveAdmin")))),n.a.createElement(xt,{isShown:h,onClick:N,ariaLabel:C("Save"),disabled:p},p?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:v,onClose:f,text:"Are you sure you want to dismiss this admin?",confirmLabel:"Dismiss",confirmHandler:I,confirmIsDestructive:!0}))}));var qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.ib)(a)}},(e,t)=>Object(u.l)(t,["openUserInfo"]))(({members:e,usersById:t,isChannel:a,openUserInfo:c})=>{const r=Object(n.p)(()=>{if(e&&t)return Object(m.Cb)(e.map(({userId:e})=>e),t)},[e,t]),s=Object(n.m)(e=>{c({id:e})},[c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},r?r.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>s(e)},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(Qe.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var $c=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.ib)(a)}})(({usersById:e,members:t,isChannel:a,onScreenSelect:c,onChatMemberSelect:r})=>{const l=Object(n.p)(()=>{if(t&&e)return Object(m.Cb)(t.filter(e=>!e.isOwner).map(({userId:e})=>e),e)},[t,e]),o=Object(n.m)(e=>{r(e),c(s.g.GroupUserPermissions)},[r,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},l?l.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>o(e)},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(Qe.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Hc=Object(n.h)(Object(c.h)(e=>({managementType:Object(d.u)(e)}))(({chatId:e,currentScreen:t,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r,onChatMemberSelect:l,managementType:o})=>{switch(t){case s.g.Initial:switch(o){case"user":return n.a.createElement(Mc,{key:e,userId:e});case"group":return n.a.createElement(Fc,{key:e,chatId:e,onScreenSelect:r});case"channel":return n.a.createElement(Tc,{key:e,chatId:e,onScreenSelect:r})}break;case s.g.ChatPrivacyType:return n.a.createElement(Dc,{chatId:e});case s.g.Discussion:return n.a.createElement(xc,{chatId:e,onScreenSelect:r});case s.g.GroupPermissions:return n.a.createElement(Lc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRemovedUsers:return n.a.createElement(Ac,{chatId:e});case s.g.GroupUserPermissionsCreate:return n.a.createElement($c,{chatId:e,onChatMemberSelect:l,onScreenSelect:r});case s.g.GroupUserPermissions:return n.a.createElement(Uc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChatAdministrators:return n.a.createElement(Rc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRecentActions:return n.a.createElement(Gc,{chatId:e});case s.g.ChatAdminRights:return n.a.createElement(zc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChannelSubscribers:case s.g.GroupMembers:return n.a.createElement(qc,{chatId:e})}}));const Vc={USD:"$",EUR:"€",GBP:"£",JPY:"¥",RUB:"₽",UAH:"₴",INR:"₹",AED:"د.إ"};function Yc(e){return e&&Vc[e]||""}const Wc=/^4[0-9]{12}(?:[0-9]{1,3})?$/,Kc=/^5[1-5][0-9]{11,14}$/,Qc=/^2[2-7][0-9]{11,14}$/;let Zc;!function(e){e[e.Default=0]="Default",e[e.Visa=1]="Visa",e[e.Mastercard=2]="Mastercard"}(Zc||(Zc={}));const Xc={[Zc.Default]:"",[Zc.Visa]:"visa",[Zc.Mastercard]:"mastercard"};function _c(e){return e=e.replace(/\s/g,""),Wc.test(e)?Zc.Visa:Kc.test(e)||Qc.test(e)?Zc.Mastercard:Zc.Default}var Jc=a(54);const er={streetLine1:"",streetLine2:"",city:"",state:"",countryIso2:"",postCode:"",fullName:"",email:"",phone:"",shipping:"",cardNumber:"",cardholder:"",expiry:"",cvv:"",billingCountry:"",billingZip:"",saveInfo:!0,saveCredentials:!1,formErrors:{}},tr=(e,t)=>{switch(t.type){case"changeAddress1":return{...e,streetLine1:t.payload,formErrors:{...e.formErrors,streetLine1:void 0}};case"changeAddress2":return{...e,streetLine2:t.payload,formErrors:{...e.formErrors,streetLine2:void 0}};case"changeCity":return{...e,city:t.payload,formErrors:{...e.formErrors,city:void 0}};case"changeState":return{...e,state:t.payload,formErrors:{...e.formErrors,state:void 0}};case"changeCountry":return{...e,countryIso2:t.payload,billingCountry:ar(t.payload),formErrors:{...e.formErrors,countryIso2:void 0}};case"changePostCode":return{...e,postCode:t.payload,formErrors:{...e.formErrors,postCode:void 0}};case"changeFullName":return{...e,fullName:t.payload,formErrors:{...e.formErrors,fullName:void 0}};case"changeEmail":return{...e,email:t.payload,formErrors:{...e.formErrors,email:void 0}};case"changePhone":return{...e,phone:t.payload,formErrors:{...e.formErrors,phone:void 0}};case"changeShipping":return{...e,shipping:t.payload};case"changeCardNumber":return{...e,cardNumber:t.payload,formErrors:{...e.formErrors,cardNumber:void 0}};case"changeCardholder":return{...e,cardholder:t.payload,formErrors:{...e.formErrors,cardholder:void 0}};case"changeExpiryDate":return{...e,expiry:t.payload,formErrors:{...e.formErrors,expiry:void 0}};case"changeCvvCode":return{...e,cvv:t.payload,formErrors:{...e.formErrors,cvv:void 0}};case"changeBillingCountry":return{...e,billingCountry:t.payload,formErrors:{...e.formErrors,billingCountry:void 0}};case"changeBillingZip":return{...e,billingZip:t.payload,formErrors:{...e.formErrors,billingZip:void 0}};case"changeSaveInfo":return{...e,saveInfo:t.payload};case"changeSaveCredentials":return{...e,saveCredentials:t.payload};case"updateUserInfo":return t.payload.countryIso2?{...e,...t.payload,billingCountry:ar(t.payload.countryIso2)}:{...e,...t.payload};case"setFormErrors":return{...e,formErrors:{...e.formErrors,...t.payload}};default:return e}};function ar(e){const t=Tt.a.find(({id:t})=>t===e);return t?t.name:""}function nr(e,t=400){Object(n.n)(()=>{o.k||setTimeout(()=>{Object(V.b)(()=>{e.current&&e.current.focus()})},t)},[e,t])}var cr=Object(n.h)(e=>{const{id:t,value:a,label:c,hasArrow:r,error:s,ref:l,placeholder:o,onChange:i,children:d}=e,m=s||c,u=Object(ce.a)("input-group",a&&"touched",s&&"error",m&&"with-label",r&&"with-arrow","input-group");return n.a.createElement("div",{className:u},n.a.createElement("select",{className:"form-control",id:t,value:a||"",onChange:i,placeholder:o||c,ref:l},d),m&&t&&n.a.createElement("label",{htmlFor:t},m))});a(293);var rr=Object(n.h)(({state:e,needEmail:t,needPhone:a,needName:c,needAddress:r,dispatch:s})=>{const l=Object(n.q)(null),o=Object(n.q)(null),i=Object(n.q)(null);Object(n.n)(()=>{i.current&&i.current.value!==e.countryIso2&&(i.current.value=e.countryIso2)},[e.countryIso2]);const d=Object(F.a)();nr(l);const m=Object(n.m)(e=>{s({type:"changeAddress1",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeAddress2",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeCity",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeState",payload:e.target.value})},[s]),p=Object(n.m)(e=>{s({type:"changeCountry",payload:e.target.value})},[s]),g=Object(n.m)(e=>{s({type:"changePostCode",payload:e.target.value})},[s]),v=Object(n.m)(e=>{s({type:"changeFullName",payload:e.target.value})},[s]),E=Object(n.m)(e=>{s({type:"changeEmail",payload:e.target.value})},[s]),f=Object(n.m)(e=>{let{value:t}=e.target;t="+"+t.replace(/\D/g,""),o.current&&(o.current.value=t),s({type:"changePhone",payload:t})},[s]),O=Object(n.m)(e=>{s({type:"changeSaveInfo",payload:e.target.value})},[s]),{formErrors:j}=e;return n.a.createElement("div",{className:"ShippingInfo"},n.a.createElement("form",null,r?n.a.createElement("div",null,n.a.createElement("h5",null,d("PaymentShippingAddress")),n.a.createElement(pe.a,{ref:l,label:"Address1 (Street)",onChange:m,value:e.streetLine1,inputMode:"text",error:j.streetLine1}),n.a.createElement(pe.a,{label:"Address2 (Street)",onChange:u,value:e.streetLine2,inputMode:"text",error:j.streetLine2}),n.a.createElement(pe.a,{label:"City",onChange:h,value:e.city,inputMode:"text",error:j.city}),n.a.createElement(pe.a,{label:"State",onChange:b,value:e.state,inputMode:"text",error:j.state}),n.a.createElement(cr,{label:"Country",placeholder:"Country",onChange:p,value:e.countryIso2,hasArrow:Boolean(!0),id:"shipping-country",error:j.countryIso2,ref:i},Tt.a.map(({name:e,id:t})=>n.a.createElement("option",{value:t,className:"county-item"},e))),n.a.createElement(pe.a,{label:"Post Code",onChange:g,value:e.postCode,inputMode:"text",error:j.postCode})):void 0,c||t||a?n.a.createElement("h5",null,d("PaymentShippingReceiver")):void 0,c&&n.a.createElement(pe.a,{label:"Full name",onChange:v,value:e.fullName,inputMode:"text",error:j.fullName}),t&&n.a.createElement(pe.a,{label:"Email",onChange:E,value:e.email,inputMode:"email",error:j.email}),a&&n.a.createElement(pe.a,{label:"Phone number",onChange:f,value:e.phone,inputMode:"tel",error:j.phone,ref:o}),n.a.createElement(_t.a,{label:d("PaymentShippingSave"),subLabel:d("PaymentShippingSaveInfo"),checked:Boolean(e.saveInfo),onChange:O})))});a(294);var sr=Object(n.h)(({state:e,shippingOptions:t,currency:a,dispatch:c})=>{Object(n.n)(()=>{t&&!e.shipping&&c({type:"changeShipping",payload:t[0].id})},[t,e.shipping,c]);const r=Object(n.m)(e=>{c({type:"changeShipping",payload:e})},[c]),s=Object(n.p)(()=>t.map(({id:e,title:t,amount:n})=>({label:t,subLabel:`${a} ${String(n/100)}`,value:e})),[t,a]);return n.a.createElement("div",{className:"Shipping"},n.a.createElement("form",null,n.a.createElement("p",null,"Select shipping method"),n.a.createElement(ca.a,{name:"shipping-options",options:s,onChange:r,selected:e.shipping})))});a(295);function lr(e,t,a,c=!1){return n.a.createElement("div",{className:"price-info-item "+(c?"price-info-item-main":"")},n.a.createElement("div",{className:"title"},e),n.a.createElement("div",{className:"value"},`${a||""} ${(t/100).toFixed(2)}`))}function or(e,t,a){return n.a.createElement("div",{className:"checkout-info-item"},n.a.createElement("i",{className:e}," "),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},t),n.a.createElement("p",{className:"data"},a)))}var ir=Object(n.h)(({invoiceContent:e,prices:t,shippingPrices:a,checkoutInfo:c,currency:r,totalPrice:s})=>{const{photoUrl:l,title:o,text:i}=e||{},{paymentMethod:d,paymentProvider:m,shippingAddress:u,name:h,phone:b,shippingMethod:p}=c||{};return n.a.createElement("div",{className:"Checkout"},n.a.createElement("div",{className:"description has-image"},l&&n.a.createElement("img",{src:l,alt:""}),n.a.createElement("div",{className:"text"},n.a.createElement("h5",null,o),n.a.createElement("p",null,i))),n.a.createElement("div",{className:"price-info"},t&&t.map(e=>lr(e.label,e.amount,r,!1)),a&&a.map(e=>lr(e.label,e.amount,r,!1)),void 0!==s&&lr("Total",s,r,!0)),n.a.createElement("div",{className:"invoice-info"},d&&or("icon-card",d,"Payment method"),m&&or("stripe-provider",m,"Payment provider"),u&&or("icon-location",u,"Shipping address"),h&&or("icon-user",h,"Name"),b&&or("icon-phone",b,"Phone number"),p&&or("icon-truck",p,"Shipping method")))});var dr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null),r=Object(n.m)(t=>{if("Backspace"===t.key&&"/"===e.charAt(e.length-1)){const t=e.slice(0,e.length-1);c.current&&(c.current.value=t)}},[e]),s=Object(n.m)(e=>{a(function(e){const t=(e=e.replace(/[^\d]/g,"").slice(0,4)).match(/.{1,2}/g);return t&&t[0]&&Number(t[0])>12&&(t[0]="12"),t&&t[0]&&2===t[0].length&&!t[1]&&(t[1]=""),t?t.join("/"):""}(e.target.value))},[a]);return n.a.createElement(pe.a,{label:"Expiry date",ref:c,onChange:s,onKeyDown:r,value:e,error:t,inputMode:"numeric",maxLength:5})}),mr=(a(296),a.p+"mastercard.4216118edafe23cc2dec7b8807ba4622.svg"),ur=a.p+"visa.e5a7c336e1deb4b92a636e2e053878c4.svg";var hr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null);nr(c);const[r,s]=Object(n.r)(Zc.Default);Object(n.n)(()=>{const t=_c(e);s(t)},[]);const l=Object(n.m)(e=>{const t=function(e){const t=(e=e.replace(/[^\d]/g,"")).match(/.{1,4}/g);return t?t.join(" "):""}(e.target.value),n=_c(e.target.value);s(n),a(t),c.current&&(c.current.value=t)},[a,c]),o=function(e){switch(e){case Zc.Mastercard:return n.a.createElement("img",{src:mr,alt:""});case Zc.Visa:return n.a.createElement("img",{src:ur,alt:""});default:return}}(r);return n.a.createElement("div",{className:"CardInput"},n.a.createElement("span",{className:"left-addon"},o),n.a.createElement(pe.a,{ref:c,label:"Card number",onChange:l,value:e,inputMode:"numeric",className:r?"has-left-addon":"",error:t,maxLength:23}))});a(297);var br=Object(n.h)(({state:e,canSaveCredentials:t,needCardholderName:a,needCountry:c,needZip:r,dispatch:s})=>{const l=Object(n.q)(null);Object(n.n)(()=>{l.current&&l.current.value!==e.billingCountry&&(l.current.value=e.billingCountry)},[e.billingCountry]);const o=Object(n.m)(e=>{s({type:"changeCardNumber",payload:e})},[s]),i=Object(n.m)(e=>{s({type:"changeCardholder",payload:e.target.value.toUpperCase()})},[s]),d=Object(n.m)(e=>{s({type:"changeExpiryDate",payload:e})},[s]),m=Object(n.m)(e=>{s({type:"changeCvvCode",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeBillingCountry",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeBillingZip",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeSaveCredentials",payload:e.target.value})},[s]),p=Object(F.a)(),{formErrors:g={}}=e;return n.a.createElement("div",{className:"PaymentInfo"},n.a.createElement("form",null,n.a.createElement("h5",null,p("PaymentCardTitle")),n.a.createElement(hr,{onChange:o,value:e.cardNumber,error:g.cardNumber}),a&&n.a.createElement(pe.a,{label:"Name on card",onChange:i,value:e.cardholder,inputMode:"text",error:g.cardholder}),n.a.createElement("section",{className:"inline-inputs"},n.a.createElement(dr,{value:e.expiry,onChange:d,error:g.expiry}),n.a.createElement(pe.a,{label:"CVV code",onChange:m,value:e.cvv,inputMode:"numeric",maxLength:3,error:g.cvv})),c||r?n.a.createElement("h5",null,p("PaymentBillingAddress")):void 0,c&&n.a.createElement(cr,{label:"Country",placeholder:"Country",onChange:u,value:e.billingCountry,hasArrow:Boolean(!0),id:"billing-country",error:g.billingCountry,ref:l},Tt.a.map(({name:e})=>n.a.createElement("option",{value:e,className:"county-item"},e))),r&&n.a.createElement(pe.a,{label:"Post Code",onChange:h,value:e.billingZip,inputMode:"text",error:g.billingZip}),t&&n.a.createElement(_t.a,{label:p("PaymentCardSavePaymentInformation"),checked:e.saveCredentials,onChange:b})))});a(176);var pr=Object(n.h)(Object(c.h)(e=>{const{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,invoice:r,invoiceContent:s,nativeProvider:l,nativeParams:o,passwordMissing:i,error:d}=e.payment,m=Boolean(r&&(!l||"stripe"!==l)),{needCardholderName:u,needCountry:h,needZip:b}=o||{},{nameRequested:p,phoneRequested:g,emailRequested:v,shippingAddressRequested:E,flexible:f,phoneToProvider:O,emailToProvider:j,currency:C,prices:y}=r||{};return{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,nativeProvider:l,passwordMissing:i,nameRequested:p,shippingAddressRequested:E,phoneRequested:g,emailRequested:v,flexible:f,phoneToProvider:O,emailToProvider:j,currency:C,prices:y,isProviderError:m,invoiceContent:s,needCardholderName:u,needCountry:h,needZip:b,error:d,globalErrors:e.errors}},(e,t)=>Object(u.l)(t,["validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError"]))(({isOpen:e,onClose:t,step:a,shippingOptions:c,savedInfo:r,canSaveCredentials:l,nameRequested:o,shippingAddressRequested:i,phoneRequested:d,emailRequested:m,phoneToProvider:u,emailToProvider:h,currency:b,passwordMissing:p,isProviderError:g,invoiceContent:v,nativeProvider:E,prices:f,needCardholderName:O,needCountry:j,needZip:C,error:y,globalErrors:k,validateRequestedInfo:N,sendPaymentForm:I,setPaymentStep:S,sendCredentialsInfo:w,clearPaymentError:P})=>{const[M,A]=jt(tr,er),D=Yc(b),[x,U]=Object(n.r)(!1),R=Object(F.a)();Object(n.n)(()=>{(a||y||k)&&U(!1)},[a,y,k]),Object(n.n)(()=>{if(y&&y.field)A({type:"setFormErrors",payload:{[y.field]:y.fieldError}});else if(k&&k.length){const e=Object(Jc.a)(k);A({type:"setFormErrors",payload:{...e}})}},[y,k,A]),Object(n.n)(()=>{if(r){const{name:e,phone:t,email:a,shippingAddress:n}=r;A({type:"updateUserInfo",payload:{fullName:e,phone:t&&"+"!==t.charAt(0)?"+"+t:t,email:a,...n||{}}})}},[r,A]);const G=Object(n.m)(()=>{P()},[P]),z=Object(n.p)(()=>a!==s.i.Checkout?0:function(e=[],t,a){const n=t?vr(t,a):[];let c=0;const r=e.concat(n||[]);return c=r.reduce((e,t)=>e+t.amount,c),c}(f,c,M.shipping),[a,M.shipping,f,c]),q=Object(n.p)(()=>{if(a===s.i.Checkout)return function(e,t,a){const n=`${function(e){const t=_c(e);return Xc[t]||""}(e.cardNumber)} *${e.cardNumber.slice(-4)}`,c=e.streetLine1?`${e.streetLine1}, ${e.city}, ${e.countryIso2}`:void 0,{phone:r,fullName:s}=e,l=t?gr(t,e.shipping):void 0,o=l?l.title:void 0;return{paymentMethod:n,paymentProvider:a,shippingAddress:c,name:s,phone:r,shippingMethod:o}}(M,c,E||"")},[a,M,c,E]);const $=Object(n.m)(()=>{const{saveInfo:e}=M,t=function(e){const{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s,fullName:l,phone:o,email:i}=e;return{name:l,phone:o,email:i,shippingAddress:{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s}}}(M);N({requestInfo:t,saveInfo:e})},[N,M]),H=Object(n.m)(()=>{const e=function(e){const{cardNumber:t,cardholder:a,expiry:n,cvv:c,billingCountry:r,billingZip:s}=e,[l,o]=n.split("/");return{data:{cardNumber:t,cardholder:a,expiryMonth:l,expiryYear:o,cvv:c,country:r,zip:s}}}(M);w({credentials:e})},[w,M]),V=Object(n.m)(()=>{I({shippingOptionId:M.shipping,saveCredentials:M.saveCredentials})},[I,M]),Y=Object(n.m)(e=>{S({step:e})},[S]),W=Object(n.m)(()=>{switch(U(!0),a){case s.i.ShippingInfo:return $();case s.i.Shipping:return Y(s.i.PaymentInfo);case s.i.PaymentInfo:return H();case s.i.Checkout:return V();default:return()=>{}}},[a,$,Y,H,V]),K=Object(n.p)(()=>{switch(a){case s.i.ShippingInfo:return R("PaymentShippingInfo");case s.i.Shipping:return R("PaymentShippingMethod");case s.i.PaymentInfo:return R("PaymentCardInfo");case s.i.Checkout:return R("PaymentCheckout");default:return""}},[a,R]),Q=Object(n.p)(()=>{switch(a){case s.i.Checkout:return`Pay ${D}${(z/100).toFixed(2)}`;default:return"Next Step"}},[a,z,D]);return g?n.a.createElement(be.a,{className:"error",isOpen:e,onClose:t},"Sorry, Telegram T doesn't support payments with this provider yet. Please use one of our mobile apps to do this.",n.a.createElement(B.a,{isText:!0,onClick:t},"OK")):n.a.createElement(be.a,{className:"PaymentModal",isOpen:e,onClose:t},n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null,K)),void 0!==a?n.a.createElement(T.a,{name:"slide",activeKey:a},()=>n.a.createElement("div",{className:"content custom-scroll"},function(e){switch(e){case s.i.ShippingInfo:return n.a.createElement(rr,{state:M,dispatch:A,needAddress:Boolean(i),needEmail:Boolean(m||h),needPhone:Boolean(d||u),needName:Boolean(o)});case s.i.Shipping:return n.a.createElement(sr,{state:M,dispatch:A,shippingOptions:c||[],currency:D});case s.i.PaymentInfo:return n.a.createElement(br,{state:M,dispatch:A,canSaveCredentials:Boolean(!p&&l),needCardholderName:O,needCountry:j,needZip:C});case s.i.Checkout:return n.a.createElement(ir,{prices:f,shippingPrices:M.shipping&&c?vr(c,M.shipping):void 0,totalPrice:z,invoiceContent:v,checkoutInfo:q,currency:D});default:return}}(a))):n.a.createElement("div",{className:"empty-content"},n.a.createElement(L.a,{color:"gray"})),n.a.createElement("div",{className:"footer"},n.a.createElement(B.a,{type:"submit",onClick:W,disabled:x,isLoading:x},Q)),y&&!y.field&&function(){if(y)return n.a.createElement(be.a,{className:"error",isOpen:Boolean(y),onClose:G},n.a.createElement("h4",null,y.description||"Error"),y.description||"Error",n.a.createElement(B.a,{isText:!0,onClick:P},"OK"))}())}));function gr(e,t){return e.find(({id:e})=>e===t)}function vr(e,t){const a=gr(e,t);return a?a.prices:void 0}var Er=Object(n.h)(Object(c.h)(e=>{const{receipt:t}=e.payment,{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}=t||{};return{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}})(({isOpen:e,onClose:t,prices:a,shippingPrices:c,totalAmount:r,currency:s,info:l,photoUrl:o,text:i,title:d,credentialsTitle:m,shippingMethod:u})=>{const h=Object(F.a)(),b=Yc(s),p=Object(n.p)(()=>function(e,t,a){if(!t)return{paymentMethod:e};const{shippingAddress:n}=t,c=n&&n.streetLine1?`${n.streetLine1}, ${n.city}, ${n.countryIso2}`:void 0,{phone:r,name:s}=t;return{paymentMethod:e,paymentProvider:"Stripe",shippingAddress:c,name:s,phone:r,shippingMethod:a}}(m,l,u),[l,u,m]);return n.a.createElement(be.a,{className:"PaymentModal PaymentModal-receipt",isOpen:e,onClose:t},n.a.createElement("div",null,n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null," ",h("PaymentReceipt")," ")),n.a.createElement("div",{className:"receipt-content custom-scroll"},n.a.createElement(ir,{prices:a,shippingPrices:c,totalPrice:r,invoiceContent:{photoUrl:o,text:i,title:d},checkoutInfo:p,currency:b}))))}))},,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){"use strict";a.d(t,"a",(function(){return s}));var n=a(4),c=a(48);const r={MonkeyIdle:a.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:a.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:a.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:a.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:a.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:a.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:a.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function s(e){const t=r[e].replace(window.location.origin,"");return c.b("file"+t,n.ApiMediaFormat.Lottie)}},,,,function(e,t,a){"use strict";var n=a(0),c=a(8),r=a(1),s=a(14),l=a(94),o=a(25),i=a(99),d=a(16);a(141);const m={type:"blob",quality:.8,format:"jpeg",circle:!1};let u,h,b;var p=Object(n.h)(({file:e,onChange:t,onClose:c})=>{const[p,g]=Object(n.r)(!1);Object(n.n)(()=>{e&&(p?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:a,offsetHeight:n}=t;b=new u(t,{enableZoom:!0,boundary:{width:a,height:n},viewport:{width:a-16,height:n-16,type:"circle"}});const c=await Object(s.a)(e);await b.bind({url:c})}catch(e){r.o&&console.error(e)}}(e):async function(){return h||(h=Promise.all([a.e(5),a.e(7)]).then(a.bind(null,304)),u=(await h).default),h}().then(()=>g(!0)))},[e,p]);const v=Object(l.a)();return n.a.createElement(i.a,{isOpen:Boolean(e),onClose:c,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},p?n.a.createElement("div",{id:"avatar-crop"}):n.a.createElement(d.a,null),n.a.createElement(o.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!b)return;const e=await b.result(m),a="string"==typeof e?e:Object(s.b)(e,"avatar.jpg");t(a)},ariaLabel:v("CropImage")},n.a.createElement("i",{className:"icon-check"})))});a(142);t.a=Object(n.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:a,onChange:r})=>{const[s,l]=Object(n.r)(),[o,i]=Object(n.r)(a);Object(n.n)(()=>{i(a)},[a]);const d=Object(c.a)(o&&"filled",t&&"disabled");return n.a.createElement("div",{className:"AvatarEditable"},n.a.createElement("label",{className:d,role:"button",tabIndex:0,title:e},n.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(l(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),n.a.createElement("i",{className:"icon-camera-add"}),o&&n.a.createElement("img",{src:o,alt:"Avatar"})),n.a.createElement(p,{file:s,onClose:function(){l(void 0)},onChange:function(e){l(void 0),r(e),o&&URL.revokeObjectURL(o),i(URL.createObjectURL(e))}}))})},,,,,,,,function(e,t,a){},,,,,,,,,,function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(116),l=a(106);a(128);const o=[0,50],i=[0,20],d=[20,0],m=r.f?c.pb:c.ob;t.a=Object(n.h)(({isPasswordVisible:e,isBig:t})=>{const[a,r]=Object(n.r)(),[u,h]=Object(n.r)(),[b,p]=Object(n.r)(!1),[g,v]=Object(n.r)(!1);Object(n.n)(()=>{a?setTimeout(()=>v(!0),2e3):Object(s.a)("MonkeyClose").then(r)},[a]),Object(n.n)(()=>{u||Object(s.a)("MonkeyPeek").then(h)},[u]);const E=Object(n.m)(()=>p(!0),[]);return n.a.createElement("div",{id:"monkey",className:t?"big":""},!b&&n.a.createElement("div",{className:"monkey-preview"}),a&&n.a.createElement(l.a,{id:"closeMonkey",size:t?c.zb:m,className:g?"hidden":"shown",animationData:a,playSegment:o,noLoop:!0,onLoad:E}),u&&n.a.createElement(l.a,{id:"peekMonkey",size:t?c.zb:m,className:g?"shown":"hidden",animationData:u,playSegment:e?i:d,noLoop:!0}))})},function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(8),l=a(25);const o=r.f?550:400;t.a=Object(n.h)(({isLoading:e=!1,isPasswordVisible:t,error:a,hint:i,placeholder:d="Password",submitLabel:m="Next",clearError:u,onChangePasswordVisibility:h,onInputChange:b,onSubmit:p})=>{const g=Object(n.q)(null),[v,E]=Object(n.r)(""),[f,O]=Object(n.r)(!1);return Object(n.n)(()=>{r.k||setTimeout(()=>{g.current.focus()},o)},[]),Object(n.n)(()=>{a&&requestAnimationFrame(()=>{g.current.focus(),g.current.select()})},[a]),n.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||f&&p(v)},autoComplete:"off"},n.a.createElement("div",{className:Object(s.a)("input-group password-input",v&&"touched",a&&"error")},n.a.createElement("input",{ref:g,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:v||"",autoComplete:"current-password",onChange:function(e){a&&u();const{target:t}=e;E(t.value),O(t.value.length>=c.X),b&&b(t.value)}}),n.a.createElement("label",null,a||i||d),n.a.createElement("div",{className:"toggle-password",onClick:function(){h(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},n.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),f&&n.a.createElement(l.a,{type:"submit",ripple:!0,isLoading:e},m))})},,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,function(e,t,a){},,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){}])]); -//# sourceMappingURL=2.28b104a90f1c1a985b2b.js.map \ No newline at end of file +(window.webpackJsonp=window.webpackJsonp||[]).push([[2],Array(92).concat([function(e,t,a){"use strict";a.r(t),a.d(t,"MediaViewer",(function(){return de})),a.d(t,"ForwardPicker",(function(){return Oe})),a.d(t,"Errors",(function(){return ye})),a.d(t,"Notifications",(function(){return Ne})),a.d(t,"CalendarModal",(function(){return Pe})),a.d(t,"DeleteMessageModal",(function(){return Me})),a.d(t,"PinMessageModal",(function(){return Fe})),a.d(t,"UnpinAllMessagesModal",(function(){return Le})),a.d(t,"MessageSelectToolbar",(function(){return De})),a.d(t,"LeftSearch",(function(){return Ot})),a.d(t,"Settings",(function(){return cn})),a.d(t,"ContactList",(function(){return sn})),a.d(t,"NewChat",(function(){return un})),a.d(t,"NewChatStep1",(function(){return on})),a.d(t,"NewChatStep2",(function(){return dn})),a.d(t,"ArchivedChats",(function(){return bn})),a.d(t,"ContextMenuContainer",(function(){return In})),a.d(t,"StickerSetModal",(function(){return Sn})),a.d(t,"HeaderMenuContainer",(function(){return Pn})),a.d(t,"MobileSearch",(function(){return Ln})),a.d(t,"AttachmentModal",(function(){return zn})),a.d(t,"PollModal",(function(){return $n})),a.d(t,"SymbolMenu",(function(){return bc})),a.d(t,"AttachMenu",(function(){return pc})),a.d(t,"MentionMenu",(function(){return Gn})),a.d(t,"EmojiTooltip",(function(){return gc})),a.d(t,"BotKeyboardMenu",(function(){return vc})),a.d(t,"CustomSendMenu",(function(){return Ec})),a.d(t,"DropArea",(function(){return fc.b})),a.d(t,"TextFormatter",(function(){return Oc.a})),a.d(t,"RightSearch",(function(){return Cc})),a.d(t,"StickerSearch",(function(){return Ic})),a.d(t,"GifSearch",(function(){return Sc})),a.d(t,"PollResults",(function(){return Pc})),a.d(t,"Management",(function(){return Hc})),a.d(t,"PaymentModal",(function(){return pr})),a.d(t,"ReceiptModal",(function(){return Er}));var n=a(0),c=a(2),r=a(4),s=a(19),l=a(1),o=a(7),i=a(105),d=a(6),m=a(5),u=a(3),h=a(122),b=a(42),p=a(166),g=a(31),v=a(97),E=a(111),f=a(173),O=a(38),j=a(43),C=a(135),y=a(49);function k(e,t,a,n){const{mediaEl:c}=P(t,n);if(!c)return;const{width:r}=y.a.get();let o,d=!1;if(n){const{photo:e,video:t,webPage:a}=Object(m.v)(n);d=Boolean(t),o=t?Object(m.ab)(t):Object(m.R)(e||a.photo)}else o=i.a;const{width:u,height:h}=Object(i.j)(e,d),{width:b,height:p}=Object(i.e)(u,h,o.width,o.height),g=(r-b)/2,v=function(e){const t=window.matchMedia(i.b);let a=4.125;e&&(a+=t.matches?.875:3.375);return a*i.c}(e)+(h-p)/2;let{top:E,left:f,width:O,height:j}=c.getBoundingClientRect();if([s.h.SharedMedia,s.h.Album,s.h.ScheduledAlbum,s.h.SearchResult].includes(t)){const e=function(e,t,a,n,c,r){if(e===t){const s=Math.max(c,r)*(e/t);n-=(s-c)/2,a-=(s-r)/2,c=s,r=s}else if(e>t){const a=c;n-=((c=r*(e/t))-a)/2}else if(t>e){const n=r;a-=((r=c*(t/e))-n)/2}return{top:a,left:n,width:c,height:r}}(b,p,E,f,O,j);E=e.top,f=e.left,O=e.width,j=e.height}const C=f+O/2-(g+b/2),k=E+j/2-(v+p/2),N=O/b,S=j/p,F=I(a||c);w(F,{top:v+"px",left:g+"px",width:b+"px",height:p+"px",transform:`translate3d(${C}px, ${k}px, 0) scale(${N}, ${S})`}),M(F,t),document.body.classList.add("ghost-animating"),requestAnimationFrame(()=>{document.body.appendChild(F),requestAnimationFrame(()=>{F.style.transform="",function(e){e.firstChild.style.objectFit="default",e.classList.remove("rounded-corners","circle")}(F),setTimeout(()=>{requestAnimationFrame(()=>{document.body.removeChild(F),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function N(e,t,a){const{container:n,mediaEl:c}=P(e,a);if(!c)return;const r=document.getElementById("MediaViewer").querySelector(".active .media-viewer-content img, .active .media-viewer-content video");if(!r||!c)return;const{top:o,left:i,width:d,height:m}=r.getBoundingClientRect(),{top:u,left:h,width:b,height:p}=c.getBoundingClientRect();let g=u;if(!function(e){if("none"===e.style.display)return!1;const t=e.getBoundingClientRect(),{height:a}=y.a.get();return t.top<=a&&t.top+t.height>=0}(n)){const{height:e}=y.a.get();g=uO?f=O:O>f&&(O=f));const C=I(t||c,e===s.h.ProfileAvatar);w(C,{top:g+"px",left:h+"px",width:b+"px",height:p+"px",transform:`translate3d(${v}px, ${E}px, 0) scale(${f}, ${O})`}),requestAnimationFrame(()=>{document.body.classList.add("ghost-animating"),document.body.appendChild(C),requestAnimationFrame(()=>{C.style.transform="",j&&(C.style.opacity="0"),M(C,e),setTimeout(()=>{requestAnimationFrame(()=>{document.body.removeChild(C),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function I(e,t=!1){const a=document.createElement("div");a.classList.add("ghost");const n=new Image;if("string"==typeof e?n.src=e:e instanceof HTMLVideoElement?n.src=e.poster:n.src=e.src,a.appendChild(n),t){a.classList.add("ProfileInfo");const e=document.querySelector("#RightColumn .ProfileInfo .info");e&&a.appendChild(e.cloneNode(!0))}return a}function S(e,t){const a=document.querySelector(".active > .MessageList");let n=e.offsetTop+t.closest(".content-inner, .WebPage").offsetTop;return e.id.includes("album-media-")&&(n+=e.parentElement.offsetTop+e.closest(".Message").offsetTop),n>a.scrollTop&&n+t.offsetHeight{if(n&&t)return{sender:Object(m.kb)(t)?Object(d.Db)(e,t):Object(d.f)(e,t)};if(!a||!t)return{};const c=Object(d.k)(e,t,a);return{message:c,sender:c&&Object(d.qb)(e,c)}},(e,t)=>Object(u.l)(t,["closeMediaViewer","focusMessage"]))(({chatId:e,messageId:t,sender:a,isAvatar:c,message:r,closeMediaViewer:s,focusMessage:l})=>{const o=Object(n.m)(()=>{s(),l({chatId:e,messageId:t})},[e,l,t,s]);if(Object(F.a)(),!a||!r&&!c)return;const i=a.id<0,d=Object(m.U)(a);return n.a.createElement("div",{className:"SenderInfo",onClick:o},i?n.a.createElement(U.a,{key:a.id,size:"medium",chat:a}):n.a.createElement(U.a,{key:a.id,size:"medium",user:a}),n.a.createElement("div",{className:"meta"},n.a.createElement("div",{className:"title"},d&&Object(x.a)(d)),n.a.createElement("div",{className:"date"},c?"Profile photo":Object(D.d)(1e3*r.date))))}),G=a(167),z=a(56),q=a(34),$=a(112);a(243);var H=({mediaData:e,isVideo:t,isZoomed:a,message:c,fileName:r,isAvatar:s,onCloseMediaViewer:l,onForward:i,onZoomToggle:d})=>{const[u,h]=Object(n.r)(!1),b=t&&c?Object(m.D)(c,"download"):void 0,{mediaData:p,downloadProgress:g}=Object(E.a)(b,!u);Object(n.n)(()=>{u&&p&&(Object(G.a)(p,r),h(!1))},[r,p,u]),Object(n.n)(()=>{h(!1)},[b]);const v=Object(n.m)(e=>{e.stopPropagation(),h(e=>!e)},[]),f=Object(F.a)(),O=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",className:t?"active":void 0,onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]);return o.f?n.a.createElement("div",{className:"MediaViewerActions-mobile"},n.a.createElement(z.a,{trigger:O,positionX:"right"},!s&&n.a.createElement(q.a,{icon:"forward",onClick:i},f("Forward")),t?n.a.createElement(q.a,{icon:u?"close":"download",onClick:v},u?Math.round(100*g)+"% Downloading...":"Download"):n.a.createElement(q.a,{icon:"download",href:e,download:r},f("AccActionDownload"))),u&&n.a.createElement($.a,{progress:g,size:"s",noCross:!0})):n.a.createElement("div",{className:"MediaViewerActions"},!s&&n.a.createElement(n.a.Fragment,null,n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("Forward"),onClick:i},n.a.createElement("i",{className:"icon-forward"}))),t?n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("AccActionDownload"),onClick:v},u?n.a.createElement($.a,{progress:g,size:"s",onClick:v}):n.a.createElement("i",{className:"icon-download"})):n.a.createElement(B.a,{href:e,download:r,round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("AccActionDownload")},n.a.createElement("i",{className:"icon-download"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:a?"Zoom Out":"Zoom In",onClick:d},n.a.createElement("i",{className:a?"icon-zoom-out":"icon-zoom-in"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:f("Close"),onClick:l},n.a.createElement("i",{className:"icon-close"})))},V=a(9);a(244);var Y=({text:e="",isHideable:t,onClick:a})=>{const[c,r]=Object(n.r)(!1);return Object(n.n)(()=>{const e=document.querySelector(".MediaViewerFooter .media-text"),t=()=>{const t=e?e.clientHeight:0;r(t>2*i.c)};t();const a=Object(V.g)(t,500,!0);return window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[]),n.a.createElement("div",{className:"MediaViewerFooter "+(t?"hideable":""),onClick:function(t){e&&t.stopPropagation()}},e&&n.a.createElement("div",{className:"media-viewer-footer-content",onClick:a},n.a.createElement("p",{className:"media-text custom-scroll "+(c?"multiline":"")},e)))},W=a(29),K=a(125);const Q=function(){if(void 0!==document.fullscreenElement)return"fullscreenElement";if(void 0!==document.mozFullScreenElement)return"mozFullScreenElement";if(void 0!==document.webkitFullscreenElement)return"webkitFullscreenElement";return""}();var Z=a(137),X=a(124);const _=["bytes","kB","MB","GB","TB","PB"];var J=e=>{const t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**Math.floor(t)).toFixed(1)} ${_[t]}`};a(245);const ee=e=>{e.stopPropagation()};var te=({bufferedProgress:e,currentTime:t,duration:a,fileSize:c,isForceVisible:r,isForceMobileVersion:s,isPlayed:l,isFullscreenSupported:i,isFullscreen:d,onChangeFullscreen:m,onPlayPause:u,onSeek:h})=>{const[b,p]=Object(n.r)(!0);Object(n.n)(()=>{r&&p(r)},[r]),Object(n.n)(()=>{let e;return r||(o.f?p(!1):e=window.setTimeout(()=>{p(!1)},800)),()=>{e&&window.clearTimeout(e)}},[r]),Object(n.n)(()=>((b||r)&&document.body.classList.add("video-controls-visible"),()=>{document.body.classList.remove("video-controls-visible")}),[r,b]);const g=Object(F.a)();var v,E;if(b||r)return n.a.createElement("div",{className:"VideoPlayerControls "+(s?"mobile":""),onClick:ee},function(e,t,a,c){const r=e/t*100,s=100*a;return n.a.createElement("div",{className:"player-seekline"},n.a.createElement("div",{className:"player-seekline-track"},n.a.createElement("div",{className:"player-seekline-buffered",style:`width: ${s||0}%`}),n.a.createElement("div",{className:"player-seekline-played",style:`width: ${r||0}%`}),n.a.createElement("input",{min:"0",max:"100",step:.01,type:"range",onInput:c,className:"player-seekline-input",value:r||0})))}(t,a,e,h),n.a.createElement(B.a,{ariaLabel:g("AccActionPlay"),size:"tiny",ripple:!o.f,color:"translucent-white",className:"play",onClick:u},n.a.createElement("i",{className:l?"icon-pause":"icon-play"})),function(e,t){return n.a.createElement("div",{className:"player-time"},`${Object(D.e)(e)} / ${Object(D.e)(t)}`)}(t,a),e<1&&(v=e,E=c,n.a.createElement("div",{className:"player-file-size"},`${J(E*v)} / ${J(E)}`)),i&&n.a.createElement(B.a,{ariaLabel:"Fullscreen",size:"tiny",color:"translucent-white",className:"fullscreen",onClick:m},n.a.createElement("i",{className:""+(d?"icon-smallscreen":"icon-fullscreen")})))};a(246);function ae(){return(ae=Object.assign||function(e){for(var t=1;t{const m=Object(n.q)(null),[u,h]=Object(n.r)(!o.k||!o.d),[b,p]=Object(n.r)(0),[g,v]=Object(n.r)(!0),[E,f,O]=function(e,t){const[a,c]=Object(n.r)(Boolean(Q&&document[Q]));return Object(n.o)(()=>{const a=()=>{c(Boolean(Q&&document[Q]))},n=()=>{c(!0)},r=()=>{c(!1),t(!1)},s=e.current;return document.addEventListener("fullscreenchange",a,!1),document.addEventListener("webkitfullscreenchange",a,!1),document.addEventListener("mozfullscreenchange",a,!1),s&&(s.addEventListener("webkitbeginfullscreen",n,!1),s.addEventListener("webkitendfullscreen",r,!1)),()=>{document.removeEventListener("fullscreenchange",a,!1),document.removeEventListener("webkitfullscreenchange",a,!1),document.removeEventListener("mozfullscreenchange",a,!1),s&&(s.removeEventListener("webkitbeginfullscreen",n,!1),s.removeEventListener("webkitendfullscreen",r,!1))}},[]),Q||"iOS"===o.n?[a,()=>{e.current&&(Q||"iOS"===o.n)&&(e.current.requestFullscreen?e.current.requestFullscreen():e.current.webkitRequestFullscreen?e.current.webkitRequestFullscreen():e.current.webkitEnterFullscreen?e.current.webkitEnterFullscreen():e.current.mozRequestFullScreen&&e.current.mozRequestFullScreen(),c(!0))},()=>{e.current&&(document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),c(!1))}]:[!1]}(m,h),{isBuffered:j,bufferedProgress:C,bufferingHandlers:y}=Object(K.a)(),{shouldRender:k,transitionClassNames:N}=Object(W.a)(!j,void 0,void 0,"slow");Object(n.n)(()=>{i||!l?m.current.pause():e&&!o.k&&Object(X.a)(m.current)},[i,l,e]),Object(n.n)(()=>{m.current.currentTime===m.current.duration?(p(0),h(!1)):p(m.current.currentTime)},[b]);const I=Object(n.m)(e=>{e.stopPropagation(),u?(m.current.pause(),h(!1)):(m.current.play(),h(!0))},[u]);Object(Z.a)(m,[]);const S=Object(n.m)(()=>{v(!0)},[]),w=Object(n.m)(()=>{v(!1)},[]),P=Object(n.m)(e=>{p(e.currentTarget.currentTime)},[]),M=Object(n.m)(()=>{p(0),h(!1)},[]),F=Object(n.m)(()=>{E&&O?O():!E&&f&&f()},[O,E,f]),L=Object(n.m)(e=>{e.stopPropagation(),m.current.currentTime=Number(e.target.value)*m.current.duration/100},[]),A=Object(n.m)(e=>{e.stopPropagation(),v(!g)},[g]);Object(n.n)(()=>{const e=e=>{"Enter"!==e.key&&" "!==e.key||I(e)};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}},[I]);const T=c&&`width: ${c.width}px; height: ${c.height}px`,B=`background-image: url(${a})`;return n.a.createElement("div",{className:"VideoPlayer",onClick:!t&&o.f?A:void 0,onMouseOver:t?void 0:S,onMouseOut:t?void 0:w},n.a.createElement("div",{style:T},n.a.createElement("video",ae({ref:m,autoPlay:o.k,playsInline:!0,loop:t,muted:t,id:"media-viewer-video",style:B,onEnded:M},y,{onTimeUpdate:P}),e&&n.a.createElement("source",{src:e}))),k&&n.a.createElement("div",{className:["spinner-container",N].join(" ")},!j&&n.a.createElement("div",{className:"buffering"},"Buffering..."),n.a.createElement($.a,{size:"xl",progress:j?1:r,square:!0,onClick:d})),!t&&!k&&n.a.createElement(te,{isPlayed:u,bufferedProgress:C,currentTime:b,isFullscreenSupported:Boolean(f),isFullscreen:E,fileSize:s,duration:m.current?m.current.duration:0,isForceVisible:!u||g,isForceMobileVersion:c&&c.width<400,onSeek:L,onChangeFullscreen:F,onPlayPause:I}))}),ce=a(8);a(247);var re=Object(n.h)(({isShown:e,onChangeZoom:t})=>{const{transitionClassNames:a}=Object(W.a)(e),c=Object(O.a)(e),r=Object(n.q)(null),[s,l]=Object(n.r)(1),i=Object(n.q)(!1);Object(n.n)(()=>{e&&!c&&l(1.5)},[e,c]);const d=Object(n.m)(()=>{i.current=!0},[]),m=Object(n.m)(()=>{i.current=!1,1===s&&t(s,!i.current)},[t,s]);Object(n.n)(()=>{t(s,!i.current)},[s,t]);const u=Object(F.a)(),h=Object(ce.a)("ZoomControls",a);return n.a.createElement("div",{className:h},n.a.createElement(B.a,{disabled:1===s,size:"tiny",color:"translucent-white",ariaLabel:u("ZoomOut"),className:"zoom-out",ripple:!o.f,onClick:()=>{r.current&&l(Math.max(1,s-.5))}},n.a.createElement("i",{className:"icon-zoom-out"})),n.a.createElement(B.a,{disabled:3===s,size:"tiny",color:"translucent-white",ariaLabel:"Zoom In",className:"zoom-in",ripple:!o.f,onClick:()=>{r.current&&l(Math.min(3,s+.5))}},n.a.createElement("i",{className:"icon-zoom-in"})),n.a.createElement("div",{className:"seekline"},n.a.createElement("div",{className:"seekline-track"},n.a.createElement("div",{className:"seekline-played",style:`width: ${50*(s-1)}%`}),n.a.createElement("input",{ref:r,min:1,max:3,step:"0.5",value:s,type:"range",className:"seekline-input",onChange:e=>{l(Math.min(3,Math.max(Number(e.target.value),1)))},onMouseDown:d,onMouseUp:m}))))});a(248);const se=[1,0,0,1,0,0],le={1:1,1.5:1.5,2:2.2,2.5:3.3,3:5.5};var oe=Object(n.h)(({children:e,className:t,noWrap:a,canPan:c,zoomLevel:r,panDeltaX:s,panDeltaY:l,onPan:o})=>{const i=le[r]||r,[d,m]=Object(n.r)(!1),[h,b]=Object(n.r)({dx:s,dy:l,x:0,y:0}),[p,g]=Object(n.r)(se),v=Object(n.q)(null),E=Object(n.q)(null);Object(n.n)(()=>{const e=i||p[0],t=s||p[4],a=l||p[5],n=[...p];p[0]!==e&&(n[0]=e||n[0],n[3]=e||n[3]),p[4]!==t&&(n[4]=t),p[5]!==a&&(n[5]=a),Object(u.a)(p,n)||g(function(e,t,a){const n=a&&a.querySelector(".active img");if(!a||!n)return t;const c=a.getBoundingClientRect(),r=n.getBoundingClientRect(),s=r.width/e*t[0],l=r.height/e*t[3],o=(c.width-s)/2+t[4],i=(c.height-l)/2+t[5];return c.width&&c.width-150{c||g(se)},[c]),Object(n.n)(()=>{E.current&&(E.current.style.transform=`matrix(${p.toString()})`)},[a,p]);return a?e:n.a.createElement("div",{ref:v,className:"pan-wrapper "+(t||""),onMouseDown:e=>{if(!c)return;e.stopPropagation(),e.preventDefault();const t={dx:p[4],dy:p[5],x:e.pageX,y:e.pageY};b(t),m(!0),v.current&&v.current.classList.add("move")},onMouseUp:()=>{m(!1),v.current&&v.current.classList.remove("move"),o&&o(p[4],p[5])},onMouseMove:e=>{if(d){const t=function(e,t){const a=[...p],n=h.x-e,c=h.y-t;return a[4]=h.dx-n,a[5]=h.dy-c,a}(e.pageX,e.pageY);g(t),E.current&&(E.current.style.transform=`matrix(${p.toString()})`)}}},n.a.createElement("div",{ref:E,className:"pan-container"},e))});a(249);function ie(e,t){return e?n.a.createElement("img",{src:e,alt:"",style:t?`width: ${t.width}px`:"",draggable:!1}):n.a.createElement("div",{className:"spinner-wrapper",style:t?`width: ${t.width}px`:""},n.a.createElement(L.a,{color:"white"}))}var de=Object(n.h)(Object(c.h)(e=>{const{chatId:t,threadId:a,messageId:n,avatarOwnerId:c,profilePhotoIndex:r,origin:l}=e.mediaViewer,{animationLevel:o}=e.settings.byKey;if(l===s.h.SearchResult){if(!t||!n)return{animationLevel:o};const a=Object(d.k)(e,t,n);return a?{chatId:t,messageId:n,senderId:a.senderId,origin:l,message:a,animationLevel:o}:{animationLevel:o}}if(c){return{messageId:-1,senderId:c,avatarOwner:Object(d.Db)(e,c)||Object(d.f)(e,c),profilePhotoIndex:r||0,animationLevel:o,origin:l}}if(!(t&&a&&n))return{animationLevel:o};let i,m,u;if(i=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.mb)(e,t,n):Object(d.k)(e,t,n),!i)return{animationLevel:o};if(m=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.nb)(e,t):Object(d.m)(e,t),l===s.h.Inline||l===s.h.Album)u=Object(d.db)(e,t,a)||Object(d.X)(e,t,a);else if(l===s.h.SharedMedia){const t=Object(d.v)(e),{foundIds:a}=t&&t.resultsByType&&t.resultsByType.media||{};u=a}return{chatId:t,threadId:a,messageId:n,senderId:i.senderId,origin:l,message:i,chatMessages:m,collectionIds:u,animationLevel:o}},(e,t)=>Object(u.l)(t,["openMediaViewer","closeMediaViewer","openForwardMenu","focusMessage"]))(({chatId:e,threadId:t,messageId:a,senderId:c,origin:d,avatarOwner:u,profilePhotoIndex:y,message:I,chatMessages:S,collectionIds:w,openMediaViewer:P,closeMediaViewer:M,openForwardMenu:L,focusMessage:D,animationLevel:x})=>{const U=Object(n.q)(null),G=Boolean(u||a),z=I?Object(m.Q)(I):void 0,q=I?Object(m.G)(I):void 0,$=I?Object(m.O)(I):void 0,V=Boolean(z),W=Boolean(q||z),K=Boolean($),Q=$?$.isGif:void 0,Z=d===s.h.SharedMedia,X=d===s.h.SearchResult,_=x>=1?"mv-slide":"none",J=2===x?"slide-fade":"none",ee=2===x,te=u?`avatar${u.id}-${y}.jpg`:I&&Object(m.B)(I),ae=Object(O.a)(c),[ce,se]=Object(n.r)(!1),[le,de]=Object(n.r)(!1),[me,ue]=Object(n.r)(1),[he,be]=Object(n.r)({x:0,y:0}),pe=Object(n.p)(()=>V&&a?[a]:Object(m.i)(S||{},w||[],Z),[V,a,S,w,Z]),ge=a?pe.indexOf(a):-1,ve=0===ge||-1===ge,Ee=ge===pe.length-1||-1===ge;function fe(e){if(u&&void 0!==y){const{photos:t}=u;return t&&t[y]?`photo${t[y].id}?size=c`:Object(m.f)(u,e?"big":"normal")}return I&&Object(m.D)(I,e?"viewerFull":"viewerPreview")}!G||ae&&ae===c&&U.current||(U.current=ge);const Oe=Object(v.a)(I&&(Z||X)&&Object(m.D)(I,"pictogram"),void 0,r.ApiMediaFormat.BlobUrl,void 0,ee&&350),je=fe(),Ce=Object(v.a)(je,void 0,u&&je&&je.startsWith("profilePhoto")?r.ApiMediaFormat.DataUri:r.ApiMediaFormat.BlobUrl,void 0,ee&&350),{mediaData:ye,downloadProgress:ke}=Object(E.a)(fe(!0),void 0,I&&Object(m.C)(I,"viewerFull"),void 0,ee&&350),Ne=q||$?(q||$).blobUrl:void 0;let Ie=!K&&(Ne||ye)||Ce||Oe;const Se=Object(f.a)(!Ie&&I&&Object(m.E)(I));Ie||d===s.h.SearchResult||(Ie=Se);const we=W?Object(m.R)(V?Object(m.Q)(I):Object(m.G)(I)):void 0,Pe=K?Object(m.ab)(Object(m.O)(I)):void 0;Object(n.n)(()=>{o.f&&document.body.classList.toggle("is-media-viewer-open",G)},[G]);const Me=Object(g.a)();Object(n.n)(()=>{const e=window.matchMedia(i.b);return"function"==typeof e.addEventListener?e.addEventListener("change",Me):"function"==typeof e.addListener&&e.addListener(Me),()=>{"function"==typeof e.removeEventListener?e.removeEventListener("change",Me):"function"==typeof e.removeListener&&e.removeListener(Me)}},[Me]);const Fe=Object(O.a)(I),Le=Object(O.a)(d),Ae=Object(O.a)(u),Te=Object(O.a)(Ie);Object(n.n)(()=>{if(ee&&G&&!Fe&&!Ae){Object(j.b)(350+l.c);const e=I?Object(C.a)(I):void 0;k(Boolean(e),d,Ie,I)}ee&&!G&&(Fe||Ae)&&(Object(j.b)(350+l.c),N(Le,Te,Fe||void 0))},[ee,G,d,Le,I,Fe,Ae,Ie,Te]),Object(n.n)(()=>{let e;return le?se(!0):e=window.setTimeout(()=>{se(!1)},350),()=>{e&&window.clearTimeout(e)}},[le]);const Be=()=>{de(!1),ue(1),be({x:0,y:0})},De=Object(n.m)(()=>{de(!le),ue(le?1:1.5),le&&be({x:0,y:0})},[le]),xe=Object(n.m)((e,t=!1)=>{ue(e),1===e&&t&&Be()},[]),Ue=Object(n.m)(()=>{M(),Be()},[M]),Re=Object(n.m)(()=>{Ue(),D({chatId:e,threadId:t,messageId:a})},[Ue,e,t,D,a]),Ge=Object(n.m)(()=>{L({fromChatId:e,messageIds:[a]}),Be()},[L,e,a]);Object(n.n)(()=>G?Object(b.a)(()=>{le?Be():Ue()}):void 0,[Ue,G,le]),Object(n.n)(()=>{K&&!Q&&Object(p.b)()},[Q,K]);const ze=Object(n.m)((e,t)=>{let a=pe.indexOf(e);return(-1===t&&a>0||1===t&&a{ve||P({chatId:e,threadId:t,messageId:a?ze(a,-1):void 0,origin:d})},[e,t,ze,ve,a,P,d]),$e=Object(n.m)(()=>{Ee||P({chatId:e,threadId:t,messageId:a?ze(a,1):void 0,origin:d})},[e,t,ze,Ee,a,P,d]);Object(n.n)(()=>{const e=e=>{switch(e.key){case"Left":case"ArrowLeft":qe();break;case"Right":case"ArrowRight":$e()}};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}}),Object(n.n)(()=>{const e=document.querySelector(".slide-container > .active, .slide-container > .to");if(!e)return;const t=Q&&!o.d;return Object(h.b)(e,{excludedClosestSelector:".backdrop, .navigation, .media-viewer-head, .media-viewer-footer"+(t?"":", .VideoPlayer"),onClick:()=>{le||Ue()},onSwipe:o.k?(e,t)=>{t===h.a.Right?qe():t===h.a.Left?$e():Ue()}:void 0})},[Ue,Q,le,$e,qe,ce]);const He=Object(n.m)((e,t)=>{be({x:e,y:t})},[]),Ve=Object(F.a)();function Ye(t){if(u)return n.a.createElement("div",{key:e,className:"media-viewer-content"},ie(ye||Ce,Object(i.g)(i.a,!1)));if(I){const e=Object(C.a)(I),c=Boolean(e);return n.a.createElement("div",{key:a,className:"media-viewer-content "+(c?"has-footer":"")},W&&ie(Ne||ye||Ce||Oe,I&&Object(i.g)(we,c)),K&&n.a.createElement(ne,{key:a,url:Ne||ye,isGif:Q,posterData:Ie,posterSize:I&&Object(i.g)(Pe,c,!0),downloadProgress:ke,fileSize:$.size,isMediaViewerOpen:G,noPlay:!t,onClose:Ue}),e&&n.a.createElement(Y,{text:e,onClick:Re,isHideable:K}))}}function We(){return n.a.createElement(R,{key:u?u.id:a,chatId:u?u.id:e,messageId:a,isAvatar:Boolean(u)})}return n.a.createElement(A.a,{id:"MediaViewer",className:le?"zoomed":"",isOpen:G},()=>n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"media-viewer-head"},o.f&&n.a.createElement(B.a,{className:"media-viewer-close",round:!0,size:"smaller",color:"translucent-white",ariaLabel:Ve("Close"),onClick:Ue},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(T.a,{activeKey:U.current,name:J},We),n.a.createElement(H,{mediaData:ye||Ce,isVideo:K,isZoomed:le,message:I,fileName:te,onCloseMediaViewer:Ue,onForward:Ge,onZoomToggle:De,isAvatar:Boolean(u)})),n.a.createElement(oe,{noWrap:!ce,canPan:le,panDeltaX:he.x,panDeltaY:he.y,zoomLevel:me,onPan:He},n.a.createElement(T.a,{className:"slide-container",activeKey:ge,name:_},Ye)),!ve&&n.a.createElement("button",{type:"button",className:"navigation prev "+(K&&!Q&&"inline"),"aria-label":Ve("AccDescrPrevious"),onClick:qe}),!Ee&&n.a.createElement("button",{type:"button",className:"navigation next "+(K&&!Q&&"inline"),"aria-label":Ve("Next"),onClick:$e}),n.a.createElement(re,{isShown:le,onChangeZoom:xe})))})),me=a(46),ue=a(118),he=a(16),be=a(99),pe=a(40),ge=a(102),ve=a(95),Ee=a(98),fe=a(114);a(250);var Oe=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a},currentUserId:n}=e;return{chatsById:t,activeListIds:a.active,archivedListIds:a.archived,currentUserId:n}},(e,t)=>Object(u.l)(t,["setForwardChatId","exitForwardMode","loadMoreChats"]))(({chatsById:e,activeListIds:t,archivedListIds:a,currentUserId:c,isOpen:s,setForwardChatId:l,exitForwardMode:i,loadMoreChats:d})=>{const[u,h]=Object(n.r)(""),b=Object(n.q)(null);Object(n.n)(()=>{s?o.f||setTimeout(()=>{requestAnimationFrame(()=>{b.current&&b.current.focus()})},500):(b.current&&b.current.blur(),setTimeout(()=>{h("")},300))},[s]);const p=Object(n.p)(()=>{const n=[...t||[],...a||[]];return Object(m.Bb)([...n.filter(t=>{const a=e[t];return!a||!!Object(m.e)(a,r.MAIN_THREAD_ID)&&(!u||Object(me.a)(Object(m.l)(e[t],void 0,t===c),u))})],e,void 0,c?[c]:void 0)},[t,a,e,c,u]),[g,v]=Object(ue.a)(d,p,Boolean(u)),E=Object(n.m)(e=>{h(e.currentTarget.value)},[]),f=Object(F.a)(),O=n.a.createElement("div",{className:"modal-header"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:f("Close"),onClick:i},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(pe.a,{ref:b,value:u,onChange:E,placeholder:f("ForwardTo")}));return n.a.createElement(be.a,{isOpen:s,onClose:i,className:"ForwardPicker",header:O},g&&g.length?n.a.createElement(ge.a,{className:"picker-list custom-scroll",items:g,onLoadMore:v,noScrollRestore:Boolean(u)},g.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable force-rounded-corners",onClick:()=>l({id:e})},Object(m.kb)(e)?n.a.createElement(Ee.a,{status:e===c?f("SavedMessagesInfo"):void 0,userId:e}):n.a.createElement(fe.a,{chatId:e})))):g&&!g.length?n.a.createElement("p",{className:"no-results"},"Sorry, nothing found."):n.a.createElement(he.a,null))})),je=a(159);a(251);function Ce(e){return e.isSlowMode?"Slowmode enabled":"Something went wrong"}var ye=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["errors"]),(e,t)=>Object(u.l)(t,["dismissError"]))(({errors:e,dismissError:t})=>{const a=Object(F.a)();if(e.length)return n.a.createElement("div",{id:"Errors"},e.map(e=>n.a.createElement(be.a,{isOpen:!0,onClose:t,className:"error",title:Ce(e)},n.a.createElement("p",null,Object(je.a)(e)),n.a.createElement(B.a,{isText:!0,onClick:t},a("OK")))))})),ke=a(170);var Ne=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["notifications"]),(e,t)=>Object(u.l)(t,["dismissNotification"]))(({notifications:e,dismissNotification:t})=>{if(e.length)return n.a.createElement("div",{id:"Notifications"},e.map(({message:e})=>n.a.createElement(ke.a,{message:Object(x.a)(e,["emoji","br","links"]),onDismiss:t})))}));a(252);const Ie=["M","T","W","T","F","S","S"];function Se(e,t,a,n,c){const r=new Date(e,t,a,0,0,0,0),s=n&&new Date(n.getFullYear(),n.getMonth(),n.getDate(),0,0,0,0),l=c&&new Date(c.getFullYear(),c.getMonth(),c.getDate(),0,0,0,0);return!!(l&&r>l)||!!(s&&r{const h=new Date,b=Object(n.p)(()=>e?new Date(e):new Date,[e]),p=t?new Date(t):void 0,[g,v]=Object(n.r)(b),[E,f]=Object(n.r)(we(b.getHours())),[O,j]=Object(n.r)(we(b.getMinutes())),C=g.getFullYear(),y=g.getMonth(),k=g.getDate();Object(n.n)(()=>{r&&v(b)},[r,b]);const N=c&&C>=h.getFullYear()&&y>=h.getMonth()||p&&C>=p.getFullYear()&&y>=p.getMonth(),I=a&&C<=h.getFullYear()&&y<=h.getMonth(),S=Object(n.p)(()=>function(e,t){const a=[],n=new Date;n.setFullYear(e),n.setMonth(t),n.setDate(1);const c=n.getDay();for(let e=1;e{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return f(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),23)),n=new Date(g.getTime());n.setHours(a),v(n);const c=we(a);f(c),e.target.value=c},[g]),P=Object(n.m)(e=>{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return j(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),59)),n=new Date(g.getTime());n.setMinutes(a),v(n);const c=we(a);j(c),e.target.value=c},[g]);return n.a.createElement(be.a,{isOpen:r,onClose:d,className:"CalendarModal"},n.a.createElement("div",{className:"container"},n.a.createElement("div",{className:"month-selector"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h4",null,Object(D.f)(g,o.f)),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",disabled:I,onClick:I?void 0:function(){v(e=>{const t=new Date(e);return t.setMonth(t.getMonth()-1),t})}},n.a.createElement("i",{className:"icon-previous"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",disabled:N,onClick:N?void 0:function(){v(e=>{const t=new Date(e);return t.setMonth(t.getMonth()+1),t})}},n.a.createElement("i",{className:"icon-next"})))),n.a.createElement("div",{className:"calendar-wrapper"},n.a.createElement("div",{className:"calendar-grid"},Ie.map(e=>n.a.createElement("div",{className:"day-button faded weekday"},n.a.createElement("span",null,e))),S.map(e=>n.a.createElement("div",{role:"button",tabIndex:0,onClick:()=>{return t=e,void v(e=>{const a=new Date(e);return a.setDate(t),a});var t},className:Object(ce.a)("day-button",Se(C,y,e,a?h:void 0,c?h:p)?"disabled":""+(e?"clickable":""),e===k&&"selected")},!!e&&n.a.createElement("span",null,e))))),s&&n.a.createElement("div",{className:"timepicker"},n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:E,onChange:w}),":",n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:O,onChange:P})),n.a.createElement("div",{className:"footer"},n.a.createElement(B.a,{onClick:function(){m(g)}},s?function(e){const t=Object(D.c)(e,!0);return`Send ${"Today"===t?t:"on "+t} at ${Object(D.h)(e)}`}(g):l),i&&n.a.createElement(B.a,{onClick:u,isText:!0},i)))});var Me=Object(n.h)(Object(c.h)((e,{message:t,isSchedule:a})=>{const{threadId:n}=Object(d.y)(e)||{},{canDeleteForAll:c}=n&&Object(d.b)(e,t,n)||{},r=Object(d.f)(e,t.chatId);return{canDeleteForAll:!a&&c,contactName:r&&Object(m.kb)(r.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(r))):void 0,willDeleteForCurrentUserOnly:r&&Object(m.hb)(r)&&!c,willDeleteForAll:r&&Object(m.mb)(r)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages"]))(({isOpen:e,isSchedule:t,message:a,album:c,canDeleteForAll:r,contactName:s,willDeleteForCurrentUserOnly:l,willDeleteForAll:o,onClose:i,deleteMessages:d,deleteScheduledMessages:m})=>{const u=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];d({messageIds:e,shouldDeleteForAll:!0}),i()},[d,a.id,i,c]),h=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];t?m({messageIds:e}):d({messageIds:e,shouldDeleteForAll:!1}),i()},[c,a.id,t,i,m,d]),b=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:i,onEnter:e&&!r?h:void 0,className:"delete",title:b("DeleteSingleMessagesTitle")},n.a.createElement("p",null,b("AreYouSureDeleteSingleMessage")),l&&n.a.createElement("p",null,"This will delete it just for you, not for other participants in the chat."),o&&n.a.createElement("p",null,"This will delete it for everyone in this chat."),r&&n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},"Delete for ",s?"me and ":"Everyone",s&&Object(x.a)(s)),n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},"Delete",r?" just for me":""),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:i},b("Cancel")))}));var Fe=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(m.kb)(t),n=Object(d.O)(e,t),c=Object(d.f)(e,t),r=!!c&&Object(m.ib)(c),s=!!c&&Object(m.hb)(c),l=!!c&&Object(m.mb)(c);return{isPrivateChat:a,isChatWithSelf:n,isChannel:r,isGroup:s,isSuperGroup:l,canPinForAll:a&&!n||l||s,contactName:c&&Object(m.kb)(c.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(c))):void 0}},(e,t)=>Object(u.l)(t,["pinMessage"]))(({isOpen:e,messageId:t,chatId:a,isChannel:c,isGroup:r,isSuperGroup:s,canPinForAll:l,contactName:o,onClose:i,pinMessage:d})=>{const m=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1}),i()},[d,a,t,i]),u=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1,isOneSide:!0,isSilent:!0}),i()},[a,t,i,d]),h=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:i,className:"pin",header:n.a.createElement("div",{className:"modal-header"},n.a.createElement("h3",{className:"modal-title"},h("PinMessageAlertTitle")))},c?n.a.createElement("p",null,h("PinMessageAlertChannel")):r||s?n.a.createElement("p",null,h("PinMessageAlert")):n.a.createElement("p",null,h("PinMessageAlertChat")),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:u},h("DialogPin")),l&&n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:m},o?"Pin for me and "+o:"Pin and notify all memebers"),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:i},h("Cancel")))}));var Le=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=t?Object(d.gb)(e,t):[];return{pinnedMessagesCount:a?a.length:0}})(({isOpen:e,pinnedMessagesCount:t,onClose:a,onUnpin:c})=>{const r=Object(F.a)();return n.a.createElement(be.a,{isOpen:e,onClose:a,className:"unpin-all",header:n.a.createElement("div",{className:"modal-header"},n.a.createElement("h3",{className:"modal-title"},r("UnpinAllMessages")))},n.a.createElement("p",null,"Do you want to unpin all ",t," messages in this chat?"),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:c},r("DialogUnpin")),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:a},r("Cancel")))})),Ae=a(28),Te=a(50);var Be=Object(n.h)(Object(c.h)((e,{isSchedule:t})=>{const{messageIds:a}=e.selectedMessages||{},{canDeleteForAll:n}=Object(d.e)(e),c=Object(d.r)(e);return{selectedMessageIds:a,canDeleteForAll:!t&&n,contactName:c&&Object(m.kb)(c.id)?Object(m.X)(Object(d.Db)(e,Object(m.T)(c))):void 0,willDeleteForCurrentUserOnly:c&&Object(m.hb)(c)&&!n,willDeleteForAll:c&&Object(m.mb)(c)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages","exitMessageSelectMode"]))(({isOpen:e,isSchedule:t,selectedMessageIds:a,canDeleteForAll:c,contactName:r,willDeleteForCurrentUserOnly:s,willDeleteForAll:l,onClose:o,deleteMessages:i,deleteScheduledMessages:d,exitMessageSelectMode:m})=>{const u=Object(n.m)(()=>{i({messageIds:a,shouldDeleteForAll:!0}),m(),o()},[i,m,a,o]),h=Object(n.m)(()=>{t?d({messageIds:a}):i({messageIds:a,shouldDeleteForAll:!1}),m(),o()},[t,m,o,d,a,i]),b=Object(F.a)();if(a)return n.a.createElement(be.a,{isOpen:e,onClose:o,onEnter:c?void 0:h,className:"delete",title:"Delete Messages?"},n.a.createElement("p",null,b("AreYouSureDeleteFewMessages")),s&&n.a.createElement("p",null,"This will delete them just for you, not for other participants in the chat."),l&&n.a.createElement("p",null,"This will delete them for everyone in this chat."),c&&n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},"Delete for ",r?"me and ":"Everyone",r&&Object(x.a)(r)),n.a.createElement(B.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},"Delete",c?" just for me":""),n.a.createElement(B.a,{className:"confirm-dialog-button",isText:!0,onClick:o},b("Cancel")))}));a(253);var De=Object(n.h)(Object(c.h)(e=>{const{type:t}=Object(d.y)(e)||{},{canDelete:a}=Object(d.e)(e);return{isSchedule:"scheduled"===t,selectedMessagesCount:Object(d.pb)(e),canDeleteMessages:a}},(e,t)=>Object(u.l)(t,["exitMessageSelectMode","openForwardMenuForSelectedMessages"]))(({canPost:e,isActive:t,messageListType:a,isSchedule:c,selectedMessagesCount:r,canDeleteMessages:s,exitMessageSelectMode:l,openForwardMenuForSelectedMessages:o})=>{const[i,d,m]=Object(Ae.a)();Object(n.n)(()=>t&&!i?Object(Te.a)({onBackspace:d,onDelete:d,onEsc:l}):void 0,[t,i,d,l]);const u=Object(O.a)(r||void 0,!0),h=t?r:u,b=Object(F.a)(),p=b("VoiceOver.Chat.MessagesSelected",h),g=Object(ce.a)("MessageSelectToolbar",e&&"with-composer",t&&"shown");return n.a.createElement("div",{className:g},n.a.createElement("div",{className:"MessageSelectToolbar-inner"},n.a.createElement(B.a,{color:"translucent",round:!0,onClick:l,ariaLabel:"Exit select mode"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("span",{className:"MessageSelectToolbar-count",title:p},p),!!r&&n.a.createElement("div",{className:"MessageSelectToolbar-actions"},"scheduled"!==a&&n.a.createElement(q.a,{icon:"forward",ariaLabel:"Forward Messages",onClick:o},n.a.createElement("span",{className:"item-text"},b("Forward"))),n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:d,disabled:!s,ariaLabel:b("EditAdminGroupDeleteMessages")},n.a.createElement("span",{className:"item-text"},b("Delete"))))),n.a.createElement(Be,{isOpen:i,isSchedule:c,onClose:m}))})),xe=a(158),Ue=a(45),Re=a(160),Ge=a(149);var ze=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(m.T)(a);return{chat:a,privateChatUser:n?Object(d.Db)(e,n):void 0,isPinned:Object(d.M)(e,t)}})(({chatId:e,chat:t,privateChatUser:a,isPinned:c,withUsername:r,onClick:s})=>{const[l,o,i]=Object(Ae.a)(),d=Object(Re.a)({chat:t,privateChatUser:a,isPinned:c,handleDelete:o});if(t)return n.a.createElement(ve.a,{className:"chat-item-clickable search-result",onClick:()=>s(e),contextActions:d},Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e,withUsername:r,avatarSize:"large"}):n.a.createElement(fe.a,{chatId:e,withUsername:r,avatarSize:"large"}),n.a.createElement(Ge.a,{isOpen:l,onClose:i,chat:t}))})),qe=a(131);a(254);const $e=Object(V.g)(e=>e(),6e4,!0);var He=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.topPeers,a=e.users.byId,{recentlyFoundChatIds:n}=e.globalSearch;return{topUserIds:t,usersById:a,recentlyFoundChatIds:n}},(e,t)=>Object(u.l)(t,["loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats"]))(({topUserIds:e,usersById:t,recentlyFoundChatIds:a,onReset:c,loadTopUsers:r,loadContactList:s,openChat:l,addRecentlyFoundChatId:o,clearRecentlyFoundChats:i})=>{const d=Object(n.q)(null);Object(n.n)(()=>{$e(()=>{r(),s()})},[r,s]),Object(qe.a)(d,!e);const u=Object(n.m)(e=>{l({id:e}),c(),setTimeout(()=>{o({id:e})},250)},[l,o,c]),h=Object(F.a)();return n.a.createElement("div",{className:"RecentContacts custom-scroll"},e&&n.a.createElement("div",{className:"top-peers-section"},n.a.createElement("div",{ref:d,className:"top-peers no-selection"},e.map(e=>n.a.createElement("div",{className:"top-peer-item",onClick:()=>u(e)},n.a.createElement(U.a,{user:t[e]}),n.a.createElement("div",{className:"top-peer-name"},Object(x.a)(Object(m.X)(t[e])||" ")))))),a&&n.a.createElement("div",{className:"search-section pt-1"},n.a.createElement("h3",{className:"section-heading mt-0 recent-chats-header"},h("Recent"),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:"Clear recent chats",onClick:i},n.a.createElement("i",{className:"icon-close"}))),a.map(e=>n.a.createElement(ze,{chatId:e,onClick:u}))))})),Ve=a(123),Ye=a(110);a(255);var We=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);if(!a)return{};const n=Object(m.T)(a);return{chat:a,...n&&{privateChatUser:Object(d.Db)(e,n)},lastSyncTime:e.lastSyncTime}},(e,t)=>Object(u.l)(t,["focusMessage"]))(({message:e,searchQuery:t,chatId:a,chat:c,privateChatUser:r,focusMessage:s,lastSyncTime:l})=>{const i=Object(m.E)(e),d=Object(v.a)(Object(m.D)(e,"micro")),u=Object(n.m)(()=>{s({chatId:a,messageId:e.id})},[a,s,e.id]);if(Object(F.a)(),c)return n.a.createElement(ve.a,{className:"ChatMessage chat-item-clickable",ripple:!o.f,onClick:u},n.a.createElement(U.a,{chat:c,user:r,withOnlineStatus:!0,isSavedMessages:r&&r.isSelf,lastSyncTime:l}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"info-row"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",null,Object(x.a)(Object(m.l)(c,r))),c.isVerified&&n.a.createElement(Ve.a,null)),n.a.createElement("div",{className:"message-date"},n.a.createElement(Ye.a,{className:"date"},Object(D.g)(1e3*e.date)))),n.a.createElement("div",{className:"subtitle"},n.a.createElement("div",{className:"message"},function(e,t,a){if(!t)return Object(x.a)(Object(m.M)(e));return n.a.createElement("span",{className:"media-preview"},n.a.createElement("img",{src:t,alt:""}),Object(m.O)(e)&&n.a.createElement("i",{className:"icon-play"}),Object(x.a)(Object(m.M)(e,!0),["emoji","highlight"],{highlight:a}))}(e,d||i,t)))))}));a(256);var Ke=Object(n.h)(({searchDate:e,onSelect:t})=>{const a=Object(n.p)(()=>function(e){if(e.match(/^\d{2,4}-\d{2}-\d{2}$/g)){const t=new Date(e);return[{date:t,text:Object(D.a)(t)}]}const t=[],a=new Date,n=a.getFullYear(),c=a.getTime()>new Date(`${n}-${e}`).getTime()?n:n-1;for(let a=0;a<8;a++){const n=new Date(`${c-a}-${e}`);t.push({date:n,text:Object(D.a)(n)})}return t}(e),[e]);return n.a.createElement("section",{className:"DateSuggest custom-scroll custom-scroll-x"},a.map(({date:e,text:a})=>n.a.createElement("div",{onClick:()=>t(e),className:"date-item",key:a},n.a.createElement("i",{className:"icon-calendar"}),n.a.createElement("span",null,a))))}),Qe=a(108),Ze=a(130),Xe=a(11);const _e=Object(V.g)(e=>e(),500,!0);var Je=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{byId:a}=e.users,{userIds:n}=e.contactList||{};if(!n)return{chatsById:t,usersById:a};const{currentUserId:c,messages:r,lastSyncTime:s}=e,{fetchingStatus:l,globalResults:o,localResults:i,resultsByType:d}=e.globalSearch,{chatIds:m,userIds:u}=o||{},{chatIds:h,userIds:b}=i||{},{byChatId:p}=r,{foundIds:g}=d&&d.text||{};return{currentUserId:c,localContactIds:n,localChatIds:h,localUserIds:b,globalChatIds:m,globalUserIds:u,foundIds:g,globalMessagesByChatId:p,chatsById:t,usersById:a,fetchingStatus:l,lastSyncTime:s}},(e,t)=>Object(u.l)(t,["openChat","addRecentlyFoundChatId","searchMessagesGlobal","setGlobalSearchChatId"]))(({searchQuery:e,searchDate:t,dateSearchQuery:a,currentUserId:c,localContactIds:r,localChatIds:l,localUserIds:i,globalChatIds:d,globalUserIds:h,foundIds:b,globalMessagesByChatId:p,chatsById:g,usersById:v,fetchingStatus:E,lastSyncTime:f,onReset:O,onSearchDateSelect:j,openChat:C,addRecentlyFoundChatId:y,searchMessagesGlobal:k,setGlobalSearchChatId:N})=>{const[I,S]=Object(n.r)(!1),[w,P]=Object(n.r)(!1),M=Object(n.m)(({direction:t})=>{f&&t===s.e.Backwards&&_e(()=>{k({type:"text",query:e})})},[f,k,e]),L=Object(n.m)(e=>{C({id:e}),e!==c&&y({id:e}),o.f||O()},[c,C,y,O]),A=Object(n.m)(e=>{N({id:e})},[N]),T=Object(n.p)(()=>{if(!e||e.startsWith("@")&&e.length<2)return Ue.a;const t=r?r.filter(t=>{const a=v[t];if(!a)return!1;const n=Object(m.Y)(a);return n&&Object(me.a)(n,e)||Object(me.a)(a.username,e)}):[];return[...c&&Object(me.a)(Object(Xe.b)("SavedMessages"),e)?[c]:[],...Object(m.Bb)(Object(u.o)([...t,...l||[],...i||[]]),g)]},[e,r,c,l,i,g,v]),B=Object(n.p)(()=>!e||e.length<4||!d||!h?Ue.a:Object(m.Bb)(Object(u.o)([...d,...h]),g,!0),[g,d,h,e]),D=Object(n.p)(()=>(e||t)&&b&&0!==b.length?b.map(e=>{const[t,a]=e.split("_").map(Number);return p&&p[t]&&p[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):Ue.a,[b,p,e,t]),x=Object(n.m)(()=>{S(!I)},[I]),U=Object(n.m)(()=>{P(!w)},[w]),R=Object(F.a)();const G=E&&!E.chats&&!E.messages&&!T.length&&!B.length&&!D.length;return e||t?n.a.createElement(ge.a,{className:"LeftSearch custom-scroll",items:D,onLoadMore:M,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Ke,{searchDate:a,onSelect:j})),G&&n.a.createElement(Qe.a,null),!!T.length&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},T.map(e=>n.a.createElement(Ze.a,{chatOrUserId:e,onClick:A,clickArg:e}))),!!T.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},T.length>3&&n.a.createElement(Ye.a,{onClick:x},I?"Show less":"Show more"),"Contacts and Chats"),T.map((e,t)=>{if(I||!(t>=3))return n.a.createElement(ze,{chatId:e,onClick:L})})),!!B.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},B.length>3&&n.a.createElement(Ye.a,{onClick:U},w?"Show less":"Show more"),"Global Search"),B.map((e,t)=>{if(w||!(t>=3))return n.a.createElement(ze,{chatId:e,withUsername:!0,onClick:L})})),!!D.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading"},R("SearchMessages")),D.map((function(t){const a=Object(m.M)(t),c=g[t.chatId];if(a&&c)return n.a.createElement(We,{chatId:t.chatId,message:t,searchQuery:e})})))):n.a.createElement(He,{onReset:O})}));const et=Object(V.g)(e=>e(),500,!0);var tt=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{currentUserId:a,messages:{byChatId:n},lastSyncTime:c}=e,{fetchingStatus:r,resultsByType:s}=e.globalSearch,{foundIds:l}=s&&s.text||{};return{currentUserId:a,foundIds:l,globalMessagesByChatId:n,chatsById:t,fetchingStatus:r,lastSyncTime:c}},(e,t)=>Object(u.l)(t,["searchMessagesGlobal"]))(({searchQuery:e,currentUserId:t,dateSearchQuery:a,foundIds:c,globalMessagesByChatId:r,chatsById:l,fetchingStatus:o,lastSyncTime:i,searchMessagesGlobal:d,onSearchDateSelect:u})=>{const h=Object(n.m)(({direction:a})=>{i&&a===s.e.Backwards&&et(()=>{d({type:"text",query:e,chatId:t})})},[t,i,d,e]),b=Object(n.p)(()=>c&&0!==c.length?c.map(e=>{const[t,a]=e.split("_").map(Number);return r&&r[t]&&r[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):Ue.a,[c,r]);const p=o&&!o.chats&&!o.messages&&!b.length;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content custom-scroll chat-list",items:b,onLoadMore:h,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Ke,{searchDate:a,onSelect:u})),p&&n.a.createElement(Qe.a,null),!!b.length&&b.map((function(t){const a=Object(m.M)(t),c=l[t.chatId];if(a&&c)return n.a.createElement(We,{chatId:t.chatId,message:t,searchQuery:e})}))))}));function at(e){return(t,a)=>{const{byId:n}=t.chats,{byId:c}=t.users,{fetchingStatus:r,resultsByType:s,chatId:l}=t.globalSearch,o="audio"!==e?e:a&&a.isVoice?"voice":"audio",{byChatId:i}=t.messages,{foundIds:d}=s&&s[o]||{};return{isLoading:void 0===d||!!r&&Boolean(r.chats||r.messages),chatsById:n,usersById:c,globalMessagesByChatId:i,foundIds:d,searchChatId:l,lastSyncTime:t.lastSyncTime}}}var nt=a(155),ct=a(109);const rt=Object(V.g)(e=>e(),500,!0);var st=Object(n.h)(Object(c.h)(at("media"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","openMediaViewer"]))(({searchQuery:e,searchChatId:t,isLoading:a,globalMessagesByChatId:c,foundIds:r,lastSyncTime:o,searchMessagesGlobal:i,openMediaViewer:d})=>{const m=Object(n.m)(({direction:a})=>{o&&a===s.e.Backwards&&rt(()=>{i({type:"media",query:e,chatId:t})})},[o,i,e,t]),u=Object(n.p)(()=>r&&c?r.map(e=>{const[t,a]=e.split("_").map(Number);return c[t]&&c[t].byId[a]}).filter(Boolean):Ue.a,[c,r]),h=Object(n.m)((e,t)=>{d({chatId:t,messageId:e,origin:s.h.SearchResult})},[d]);const b=Object(ct.a)([e],l.nb)&&!a,p=b&&r&&r.length>0&&!e,g=b&&r&&r.length>0&&e,v=Object(ce.a)("search-content custom-scroll",g&&"chat-list");return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:v,items:u,itemSelector:e?".ListItem":".Media",onLoadMore:m,noFastList:!0},!b&&n.a.createElement(he.a,null),b&&(!r||0===r.length)&&n.a.createElement(Qe.a,null),p&&n.a.createElement("div",{className:"media-list"},u.map(e=>n.a.createElement(nt.a,{key:e.id,idPrefix:"search-media",message:e,onClick:h}))),g&&u.map(e=>n.a.createElement(We,{key:e.id,chatId:e.chatId,message:e}))))}));function lt(e,t,a){const{senderId:n}=e;if(!n)return;const c=Object(m.kb)(n)?a[n]:t[n];let r=Object(m.U)(c);const s=t[e.chatId];return s&&(Object(m.kb)(n)&&c.isSelf?r="You → "+Object(m.l)(s):Object(m.jb)(s)&&(r+=" → "+Object(m.l)(s))),r}var ot=a(174);const it=Object(V.g)(e=>e(),500,!0);var dt=Object(n.h)(Object(c.h)(at("links"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:m,focusMessage:u})=>{const h=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&it(()=>{m({type:"links",query:e,chatId:t})})},[d,m,e,t]),b=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number);return o[t]&&o[t].byId[a]}).filter(Boolean):Ue.a,[o,i]),p=Object(n.m)((e,t)=>{u({chatId:t,messageId:e})},[u]);const g=Object(ct.a)([e],l.nb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:b,onLoadMore:h,noFastList:!0},!g&&n.a.createElement(he.a,null),g&&(!i||0===i.length)&&n.a.createElement(Qe.a,null),g&&i&&i.length>0&&b.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(b[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(ot.a,{key:e.id,message:e,senderTitle:lt(e,c,r),onMessageClick:p}))})))})),mt=a(152);const ut=Object(V.g)(e=>e(),500,!0);var ht=Object(n.h)(Object(c.h)(at("documents"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:u,focusMessage:h})=>{const b=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&ut(()=>{u({type:"documents",query:e,chatId:t})})},[d,u,e,t]),p=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number),n=o[t]&&o[t].byId[a];return n&&Object(m.y)(n)?n:void 0}).filter(Boolean):Ue.a,[o,i]),g=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]);const v=Object(ct.a)([e],l.nb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:p,onLoadMore:b,noFastList:!0},!v&&n.a.createElement(he.a,null),v&&(!i||0===i.length)&&n.a.createElement(Qe.a,null),v&&i&&i.length>0&&p.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(p[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(mt.a,{message:e,withDate:!0,datetime:e.date,smaller:!0,sender:lt(e,c,r),className:"scroll-item",onDateClick:g}))})))})),bt=a(157);const pt=Object(V.g)(e=>e(),500,!0);var gt=Object(n.h)(Object(c.h)(at("audio"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage","openAudioPlayer"]))(({isVoice:e,searchQuery:t,searchChatId:a,isLoading:c,chatsById:r,usersById:o,globalMessagesByChatId:i,foundIds:d,lastSyncTime:m,searchMessagesGlobal:u,focusMessage:h,openAudioPlayer:b})=>{const p=e?"voice":"audio",g=Object(n.m)(({direction:e})=>{m&&e===s.e.Backwards&&pt(()=>{u({type:p,query:t,chatId:a})})},[p,m,u,t,a]),v=Object(n.p)(()=>d&&i?d.map(e=>{const[t,a]=e.split("_").map(Number);return i[t]&&i[t].byId[a]}).filter(Boolean):Ue.a,[i,d]),E=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]),f=Object(n.m)((e,t)=>{b({chatId:t,messageId:e})},[b]);const O=Object(ct.a)([t],l.nb)&&!c;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ge.a,{className:"search-content documents-list custom-scroll",items:v,onLoadMore:g,noFastList:!0},!O&&n.a.createElement(he.a,null),O&&(!d||0===d.length)&&n.a.createElement(Qe.a,null),O&&d&&d.length>0&&v.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(v[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(new Date(1e3*e.date))),n.a.createElement(bt.a,{key:e.id,message:e,renderingFor:"searchResult",senderTitle:lt(e,r,o),date:e.date,lastSyncTime:m,className:"scroll-item",onPlay:f,onDateClick:E}))})))}));a(257);const vt=[{type:s.c.ChatList,title:"SearchAllChatsShort"},{type:s.c.Media,title:"SharedMediaTab2"},{type:s.c.Links,title:"SharedLinksTab2"},{type:s.c.Files,title:"SharedFilesTab2"},{type:s.c.Music,title:"SharedMusicTab2"},{type:s.c.Voice,title:"SharedVoiceTab2"}],Et=[{type:s.c.ChatList,title:"All Messages"},...vt.slice(1)],ft=Object.keys(s.c).length/2;var Ot=Object(n.h)(Object(c.h)(e=>{const{currentContent:t,chatId:a}=e.globalSearch;return{currentContent:t,chatId:a}},(e,t)=>Object(u.l)(t,["setGlobalSearchContent","setGlobalSearchDate"]))(({searchQuery:e,searchDate:t,currentContent:a=s.c.ChatList,chatId:c,setGlobalSearchContent:r,setGlobalSearchDate:l,onReset:o})=>{const[i,d]=Object(n.r)(0),m=Object(n.p)(()=>Object(D.l)(e),[e]),u=Object(n.m)(e=>{const t=vt[e];r({content:t.type}),d(e)},[r]),h=Object(n.m)(e=>{l({date:e.getTime()/1e3})},[l]);return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(xe.a,{activeTab:i,tabs:c?Et:vt,onSwitchTab:u}),n.a.createElement(T.a,{name:"slide",renderCount:ft,activeKey:a},()=>{switch(a){case s.c.ChatList:return c?n.a.createElement(tt,{searchQuery:e,dateSearchQuery:m,onReset:o,onSearchDateSelect:h}):n.a.createElement(Je,{searchQuery:e,searchDate:t,dateSearchQuery:m,onReset:o,onSearchDateSelect:h});case s.c.Media:return n.a.createElement(st,{searchQuery:e});case s.c.Links:return n.a.createElement(dt,{searchQuery:e});case s.c.Files:return n.a.createElement(ht,{searchQuery:e});case s.c.Music:return n.a.createElement(gt,{key:"audio",searchQuery:e});case s.c.Voice:return n.a.createElement(gt,{key:"voice",isVoice:!0,searchQuery:e});default:return}}))}));function jt(e,t){const a=Object(n.q)(e),[c,r]=Object(n.r)(t);return[c,Object(n.m)(e=>{r(t=>a.current(t,e))},[])]}const Ct=[{icon:"user",title:"FilterContacts",key:"contacts"},{icon:"non-contacts",title:"FilterNonContacts",key:"nonContacts"},{icon:"group",title:"FilterGroups",key:"groups"},{icon:"channel",title:"FilterChannels",key:"channels"},{icon:"bots",title:"FilterBots",key:"bots"}],yt=[{icon:"mute",title:"FilterMuted",key:"excludeMuted"},{icon:"archive",title:"FilterArchived",key:"excludeArchived"},{icon:"readchats",title:"FilterRead",key:"excludeRead"}],kt=["includedChatIds","bots","channels","groups","contacts","nonContacts"],Nt=["excludedChatIds","excludeArchived","excludeMuted","excludeRead"];function It(e,t,a){let n=[],c=[];if("included"===t){const{includedChatIds:t,...r}=a?e.includeFilters||{}:Object(u.l)(e.folder,kt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}else{const{excludedChatIds:t,...r}=a?e.excludeFilters||{}:Object(u.l)(e.folder,Nt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}return{selectedChatIds:n,selectedChatTypes:c}}function St(e){if(e){const{includedChatIds:t,...a}=e;if(Object.values(a).filter(Boolean).length>1||t&&t.length)return"";if(a.bots)return"Bots";if(a.groups)return"Groups";if(a.channels)return"Channels";if(a.contacts)return"Contacts";if(a.nonContacts)return"Non-Contacts"}return""}const wt={mode:"create",chatFilter:"",folder:{title:"",includedChatIds:[],excludedChatIds:[]}},Pt=(e,t)=>{switch(t.type){case"setTitle":return{...e,folder:{...e.folder,title:t.payload},isTouched:!0};case"editIncludeFilters":return{...e,includeFilters:Object(u.l)(e.folder,kt)};case"editExcludeFilters":return{...e,excludeFilters:Object(u.l)(e.folder,Nt)};case"setIncludeFilters":return{...e,includeFilters:t.payload,chatFilter:""};case"setExcludeFilters":return{...e,excludeFilters:t.payload,chatFilter:""};case"saveFilters":return e.includeFilters?{...e,folder:{...Object(u.j)(e.folder,kt),title:e.folder.title?e.folder.title:St(e.includeFilters),...e.includeFilters},includeFilters:void 0,chatFilter:"",isTouched:!0}:e.excludeFilters?{...e,folder:{...Object(u.j)(e.folder,Nt),...e.excludeFilters},excludeFilters:void 0,chatFilter:"",isTouched:!0}:e;case"editFolder":{const{id:e,description:a,...n}=t.payload;return{mode:"edit",folderId:e,folder:n,chatFilter:""}}case"setChatFilter":return{...e,chatFilter:t.payload};case"setIsLoading":return{...e,isLoading:t.payload};case"setError":return{...e,error:t.payload};case"reset":return wt;default:return e}};const Mt={currentPassword:"",password:"",hint:"",email:""},Ft=(e,t)=>{switch(t.type){case"setCurrentPassword":return{...e,currentPassword:t.payload};case"setPassword":return{...e,password:t.payload};case"setHint":return{...e,hint:t.payload};case"setEmail":return{...e,email:t.payload};case"reset":return Mt;default:return e}};var Lt=a(107);var At=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["signOut","deleteChatFolder"]))(({currentScreen:e,editedFolderId:t,onReset:a,onSaveFilter:c,signOut:r,deleteChatFolder:l})=>{const[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(n.m)(()=>{d(!0)},[]),b=Object(n.m)(()=>{d(!1)},[]),p=Object(n.m)(()=>{u(!0)},[]),g=Object(n.m)(()=>{u(!1)},[]),v=Object(n.m)(()=>{b(),r()},[b,r]),E=Object(n.m)(()=>{g(),l({id:t}),a()},[t,g,l,a]),f=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(B.a,{round:!0,ripple:!o.f,size:"smaller",color:"translucent",className:t?"active":"",onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]),O=Object(F.a)();return n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:a,ariaLabel:O("AccDescrGoBack")},n.a.createElement("i",{className:"icon-arrow-left"})),function(){switch(e){case s.m.EditProfile:return n.a.createElement("h3",null,O("EditProfile"));case s.m.General:return n.a.createElement("h3",null,O("General"));case s.m.Notifications:return n.a.createElement("h3",null,O("Notifications"));case s.m.Privacy:return n.a.createElement("h3",null,O("PrivacySettings"));case s.m.Language:return n.a.createElement("h3",null,O("Language"));case s.m.GeneralChatBackground:return n.a.createElement("h3",null,O("ChatBackground"));case s.m.GeneralChatBackgroundColor:return n.a.createElement("h3",null,O("SetColor"));case s.m.PrivacyPhoneNumber:return n.a.createElement("h3",null,O("PrivacyPhone"));case s.m.PrivacyLastSeen:return n.a.createElement("h3",null,O("PrivacyLastSeen"));case s.m.PrivacyProfilePhoto:return n.a.createElement("h3",null,O("Privacy.ProfilePhoto"));case s.m.PrivacyForwarding:return n.a.createElement("h3",null,O("PrivacyForwards"));case s.m.PrivacyGroupChats:return n.a.createElement("h3",null,O("AutodownloadGroupChats"));case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement("h3",null,O("AlwaysShareWith"));case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement("h3",null,O("NeverShareWith"));case s.m.PrivacyActiveSessions:return n.a.createElement("h3",null,O("SessionsTitle"));case s.m.PrivacyBlockedUsers:return n.a.createElement("h3",null,O("BlockedUsers"));case s.m.TwoFaDisabled:case s.m.TwoFaEnabled:return n.a.createElement("h3",null,O("TwoStepVerification"));case s.m.TwoFaNewPassword:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:return n.a.createElement("h3",null,O("EnterPassword"));case s.m.TwoFaNewPasswordConfirm:return n.a.createElement("h3",null,O("PleaseReEnterPassword"));case s.m.TwoFaNewPasswordHint:case s.m.TwoFaChangePasswordHint:return n.a.createElement("h3",null,O("PasswordHint"));case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaRecoveryEmail:return n.a.createElement("h3",null,O("RecoveryEmailTitle"));case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement("h3",null,"Recovery Email Code");case s.m.TwoFaCongratulations:return n.a.createElement("h3",null,O("TwoStepVerificationPasswordSet"));case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement("h3",null,O("PleaseEnterCurrentPassword"));case s.m.Folders:return n.a.createElement("h3",null,O("Filters"));case s.m.FoldersCreateFolder:return n.a.createElement("h3",null,O("FilterNew"));case s.m.FoldersEditFolder:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,O("FilterEdit")),t&&n.a.createElement(z.a,{className:"settings-more-menu",trigger:f,positionX:"right"},n.a.createElement(q.a,{icon:"delete",destructive:!0,onClick:p},"Delete Folder")));case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement("div",{className:"settings-main-header"},e===s.m.FoldersIncludedChats?n.a.createElement("h3",null,O("FilterInclude")):n.a.createElement("h3",null,O("FilterExclude")),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",className:"color-primary",onClick:c,ariaLabel:O("AutoDeleteConfirm")},n.a.createElement("i",{className:"icon-check"})));default:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,O("SETTINGS")),n.a.createElement(z.a,{className:"settings-more-menu",trigger:f,positionX:"right"},n.a.createElement(q.a,{icon:"logout",onClick:h},O("LogOutTitle"))))}}(),n.a.createElement(Lt.a,{isOpen:i,onClose:b,text:"Are you sure you want to log out?",confirmLabel:"Log Out",confirmHandler:v,confirmIsDestructive:!0}),n.a.createElement(Lt.a,{isOpen:m,onClose:g,text:"Are you sure you want to delete this folder?",confirmLabel:"Delete",confirmHandler:E,confirmIsDestructive:!0}))})),Tt=a(18);var Bt=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e;return{currentUser:t?Object(d.Db)(e,t):void 0}})(({onScreenSelect:e,currentUser:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-main-menu"},t&&n.a.createElement("div",{className:"settings-current-user"},n.a.createElement(U.a,{user:t,size:"jumbo"}),n.a.createElement("p",{className:"name"},Object(m.Y)(t)),n.a.createElement("p",{className:"phone"},Object(Tt.c)(t.phoneNumber))),n.a.createElement(ve.a,{icon:"edit",onClick:()=>e(s.m.EditProfile)},a("EditProfile")),n.a.createElement(ve.a,{icon:"folder",onClick:()=>e(s.m.Folders)},a("Filters")),n.a.createElement(ve.a,{icon:"settings",onClick:()=>e(s.m.General)},a("GeneralSettings")),n.a.createElement(ve.a,{icon:"unmute",onClick:()=>e(s.m.Notifications)},a("Notifications")),n.a.createElement(ve.a,{icon:"lock",onClick:()=>e(s.m.Privacy)},a("PrivacySettings")),n.a.createElement(ve.a,{icon:"language",onClick:()=>e(s.m.Language)},a("Language"))))})),Dt=a(120);a(258);var xt=({isShown:e,className:t,color:a="primary",ariaLabel:c,disabled:r,onClick:s,children:l})=>{const o=Object(ce.a)("FloatingActionButton",e&&"revealed",t);return n.a.createElement(B.a,{className:o,color:a,round:!0,disabled:r,onClick:e&&!r?s:void 0,ariaLabel:c,tabIndex:-1},l)};const Ut=/https:\/\/t\.me\/?/i,Rt=/^([a-zA-Z0-9_]+)$/,Gt=Object(V.a)(e=>e(),250,!1);var zt=Object(n.h)(({currentUsername:e,asLink:t,isLoading:a,isUsernameAvailable:c,checkUsername:r,onChange:s})=>{const[l,o]=Object(n.r)(e||""),i=Object(F.a)(),d=t?"SetUrl":"Username",m=i(t?"SetUrlPlaceholder":"Username"),[u,h]=Object(n.p)(()=>l.length?l.length<5?[void 0,m+" is too short"]:l.length>32?[void 0,m+" is too long"]:Rt.test(l)?void 0===c?[]:[c?i(d+"Available","Username"):void 0,!1===c?i(d+"InUse"):void 0]:[void 0,m+" contains invalid characters"]:[],[l,c,i,d,m]);Object(n.n)(()=>{o(e||"")},[t,e]);const b=Object(n.m)(e=>{const a=e.target.value.trim().replace(Ut,"");o(a),e.target.value=`${t?"https://t.me/":""}${a}`;const n=function(e){return e.length>=5&&e.length<=32&&Rt.test(e)}(a);n&&Gt(()=>{r({username:a})}),s&&s(!!n&&a)},[t,r,s]);return n.a.createElement(pe.a,{value:`${t?"https://t.me/":""}${l}`,onChange:b,label:m,error:h,success:u,readOnly:a})});const qt=Object(V.g)(e=>e(),6e4,!0);var $t=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e,{progress:a,isUsernameAvailable:n}=e.profileEdit||{},c=t?Object(d.Db)(e,t):void 0;if(!c)return{progress:a,isUsernameAvailable:n};const{firstName:r,lastName:s,username:l,fullInfo:o}=c,{bio:i}=o||{};return{currentAvatarHash:Object(m.f)(c),currentFirstName:r,currentLastName:s,currentBio:i,currentUsername:l,progress:a,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["loadCurrentUser","updateProfile","checkUsername"]))(({currentAvatarHash:e,currentFirstName:t,currentLastName:a,currentBio:c,currentUsername:l,progress:o,isUsernameAvailable:i,loadCurrentUser:d,updateProfile:m,checkUsername:u})=>{const[h,b]=Object(n.r)(!1),[p,g]=Object(n.r)(!1),[E,f]=Object(n.r)(),[O,j]=Object(n.r)(),[C,y]=Object(n.r)(t||""),[k,N]=Object(n.r)(a||""),[I,S]=Object(n.r)(c||""),[w,P]=Object(n.r)(l||""),M=Object(v.a)(e,!1,r.ApiMediaFormat.BlobUrl),A=o===s.j.InProgress,T=!1===w,B=Object(n.p)(()=>!T&&(Boolean(O)||p||!0===i),[O,p,T,i]);Object(n.n)(()=>{qt(()=>{d()})},[d]),Object(n.n)(()=>{j(void 0)},[M]),Object(n.n)(()=>{y(t||""),N(a||""),S(c||"")},[t,a,c]),Object(n.n)(()=>{P(l||"")},[l]),Object(n.n)(()=>{o===s.j.Complete&&(g(!1),b(!1),f(void 0))},[o]);const D=Object(n.m)(e=>{j(e)},[]),U=Object(n.m)(e=>{y(e.target.value),g(!0)},[]),R=Object(n.m)(e=>{N(e.target.value),g(!0)},[]),G=Object(n.m)(e=>{S(e.target.value),g(!0)},[]),z=Object(n.m)(e=>{P(e),b(!0)},[]),q=Object(n.m)(()=>{const e=C.trim(),t=k.trim(),a=I.trim();e.length?a.length>70?f("Bio can' be longer than 70 characters"):m({photo:O,...p&&{firstName:e,lastName:t,bio:a},...h&&{username:w}}):f("Please provide your first name")},[O,C,k,I,p,w,h,m]),$=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-edit-profile"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:M,onChange:D,title:"Edit your profile photo",disabled:A}),n.a.createElement(pe.a,{value:C,onChange:U,label:$("FirstName"),disabled:A,error:"Please provide your first name"===E?E:void 0}),n.a.createElement(pe.a,{value:k,onChange:R,label:$("LastName"),disabled:A}),n.a.createElement(pe.a,{value:I,onChange:G,label:$("UserBio"),disabled:A,error:"Bio can' be longer than 70 characters"===E?E:void 0}),n.a.createElement("p",{className:"settings-item-description"},Object(x.a)($("BioAbout"),["br","simple_markdown"]))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},$("Username")),n.a.createElement(zt,{currentUsername:w||"",isLoading:A,isUsernameAvailable:i,checkUsername:u,onChange:z}),n.a.createElement("p",{className:"settings-item-description"},Object(x.a)($("UsernameHelp"),["br","simple_markdown"])),w&&n.a.createElement("p",{className:"settings-item-description"},"This link opens a chat with you:",n.a.createElement("br",null),n.a.createElement("span",{className:"username-link"},"https://t.me/",w)))),n.a.createElement(xt,{isShown:B,onClick:q,disabled:A,ariaLabel:"Save changes"},A?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),Ht=a(116),Vt=a(106);const Yt=Object(V.g)(e=>e(),6e4,!0);var Wt=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a}}=e,{orderedIds:n,byId:c,recommended:r}=e.chatFolders;return{chatsById:t,usersById:a,orderedFolderIds:n,foldersById:c,recommendedChatFolders:r}},(e,t)=>Object(u.l)(t,["loadRecommendedChatFolders","addChatFolder","showError"]))(({onCreateFolder:e,onEditFolder:t,chatsById:a,usersById:c,orderedFolderIds:r,foldersById:s,recommendedChatFolders:o,loadRecommendedChatFolders:i,addChatFolder:d,showError:u})=>{const[h,b]=Object(n.r)(),[p,g]=Object(n.r)(!1),v=Object(n.m)(()=>g(!0),[]);Object(n.n)(()=>{h||Object(Ht.a)("FoldersAll").then(b)},[h]),Object(n.n)(()=>{Yt(()=>{i()})},[i]);const E=Object(n.m)(()=>{Object.keys(s).length>=10?u({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):e()},[s,u,e]),f=Object(F.a)(),O=Object(n.p)(()=>{if(!r)return;const e=Object.keys(a).map(Number);return r.map(t=>{const n=s[t];return{id:n.id,title:n.title,subtitle:Object(m.o)(a,c,n,e,f)}})},[r,a,s,c,f]),j=Object(n.m)(e=>{Object.keys(s).length>=10?u({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):d({folder:e})},[s,d,u]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},h&&n.a.createElement(Vt.a,{id:"settingsFoldersMain",size:l.rb,animationData:h,play:p,noLoop:!0,onLoad:v})),n.a.createElement("p",{className:"settings-item-description mb-3"},f("CreateNewFilterInfo")),n.a.createElement(B.a,{className:"with-icon mb-2",color:"primary",size:"smaller",pill:!0,fluid:!0,onClick:E},n.a.createElement("i",{className:"icon-add"}),f("CreateNewFilter"))),n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},f("Filters")),O&&O.length?O.map(e=>n.a.createElement(ve.a,{className:"mb-2",narrow:!0,multiline:!0,onClick:()=>t(s[e.id])},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.subtitle))):O&&!O.length?n.a.createElement("p",{className:"settings-item-description my-4"},"You have no folders yet."):n.a.createElement(he.a,null)),o&&!!o.length&&n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},f("FilterRecommended")),o.map(e=>n.a.createElement(ve.a,{className:"mb-2",narrow:!0,onClick:()=>j(e)},n.a.createElement("div",{className:"settings-folders-recommended-item"},n.a.createElement("div",{className:"multiline-item"},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.description)),n.a.createElement(B.a,{className:"px-3",color:"primary",size:"tiny",pill:!0,fluid:!0},f("Add")))))))}));a(259);var Kt=({count:e,itemName:t,itemPluralName:a,isLoading:c,onClick:r})=>n.a.createElement(B.a,{className:"ShowMoreButton",color:"translucent",size:"smaller",isText:!0,isLoading:c,onClick:r},n.a.createElement("i",{className:"icon-down"}),"Show ",e," more ",e>1?a||t+"s":t);const Qt="Please provide a title for this folder.",Zt="Please select at least one chat for this folder.";var Xt=Object(n.h)(Object(c.h)(e=>{const{listIds:t}=e.chats;return{loadedActiveChatIds:t.active,loadedArchivedChatIds:t.archived}},(e,t)=>Object(u.l)(t,["editChatFolder","addChatFolder","loadMoreChats"]))(({state:e,dispatch:t,onAddIncludedChats:a,onAddExcludedChats:c,onReset:r,loadedActiveChatIds:s,loadedArchivedChatIds:o,editChatFolder:i,addChatFolder:d,loadMoreChats:h})=>{const[b,p]=Object(n.r)(),[g,v]=Object(n.r)(!1),E=Object(n.m)(()=>v(!0),[]),[f,O]=Object(n.r)(!1),[j,C]=Object(n.r)(!1),{selectedChatIds:y,selectedChatTypes:k}=It(e,"included"),{selectedChatIds:N,selectedChatTypes:I}=It(e,"excluded");Object(n.n)(()=>{b||Object(Ht.a)("FoldersNew").then(p)},[b]),Object(n.n)(()=>{O(!1),C(!1)},[e.folderId]);const[S,w]=Object(n.p)(()=>{const e=new Set([...s||[],...o||[]]),t=Object(u.f)(y,e),a=Object(u.f)(N,e);return[f?t:t.slice(0,5-k.length),j?a:a.slice(0,5-I.length)]},[N,y,k,I,j,f,s,o]);Object(n.n)(()=>{(S.lengthO(!0):()=>C(!0);return n.a.createElement(n.a.Fragment,null,t.map(t=>function(e,t){const a="included"===t?Ct.find(({key:t})=>t===e):yt.find(({key:t})=>t===e);if(a)return n.a.createElement(ve.a,{key:a.key,className:"settings-folders-list-item mb-1",icon:a.icon,narrow:!0,inactive:!0},P(a.title))}(t,e)),a.map(e=>n.a.createElement(ve.a,{className:"settings-folders-list-item mb-1",narrow:!0,inactive:!0},Object(m.kb)(e)?n.a.createElement(Ee.a,{avatarSize:"small",userId:e}):n.a.createElement(fe.a,{avatarSize:"small",chatId:e}))),!c&&r>0&&n.a.createElement(Kt,{count:r,itemName:"chat",onClick:s}))}return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},b&&n.a.createElement(Vt.a,{id:"settingsFoldersEdit",size:l.rb,animationData:b,play:g&&String(e.folderId),noLoop:!0,onLoad:E})),"create"===e.mode&&n.a.createElement("p",{className:"settings-item-description mb-3"},P("FilterIncludeInfo")),n.a.createElement(pe.a,{className:"mb-0",label:P("FilterNameHint"),value:e.folder.title,onChange:function(e){const{currentTarget:a}=e;t({type:"setTitle",payload:a.value.trim()})},error:e.error&&e.error===Qt?Qt:void 0})),n.a.createElement("div",{className:"settings-item no-border pt-3"},e.error&&e.error===Zt&&n.a.createElement("p",{className:"settings-item-description color-danger mb-2"},e.error),n.a.createElement("h4",{className:"settings-item-header mb-3"},P("FilterInclude")),n.a.createElement(ve.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:a},P("FilterAddChats")),M("included")),n.a.createElement("div",{className:"settings-item no-border pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3"},P("FilterExclude")),n.a.createElement(ve.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:c},P("FilterAddChats")),M("excluded"))),n.a.createElement(xt,{isShown:!!e.isTouched,disabled:e.isLoading,onClick:function(){const{title:a}=e.folder;a?y.length||Object.keys(k).length?(t({type:"setIsLoading",payload:!0}),"edit"===e.mode?i({id:e.folderId,folderUpdate:e.folder}):d({folder:e.folder}),setTimeout(()=>{r()},500)):t({type:"setError",payload:Zt}):t({type:"setError",payload:Qt})},ariaLabel:"edit"===e.mode?"Save changes":"Create folder"},e.isLoading?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),_t=a(41);a(175),a(260);var Jt=Object(n.h)(({mode:e,chatIds:t,selectedIds:a,selectedChatTypes:c,filterValue:r,onSelectedIdsChange:s,onSelectedChatTypesChange:l,onFilterChange:o,onLoadMore:i})=>{const d=Object(n.q)(null),u="included"===e?Ct:yt,h=a.length+c.length>10,b=a.length>=100;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{d.current.focus()})},500)},[]);const p=Object(n.m)(e=>{const t=[...a];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),s(t)},[a,s]),g=Object(n.m)(e=>{const t=[...c];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),l(t)},[c,l]),v=Object(n.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]),E=Object(F.a)();const[f,O]=Object(ue.a)(i,t,Boolean(r));return n.a.createElement("div",{className:"Picker SettingsFoldersChatsPicker"},n.a.createElement("div",{className:"picker-header custom-scroll"},c.map((function(e){const t=u.find(({key:t})=>e===t);if(t)return n.a.createElement(Ze.a,{icon:t.icon,title:E(t.title),isMinimized:h,canClose:!0,onClick:g,clickArg:t.key})})),a.map((e,t)=>n.a.createElement(Ze.a,{chatOrUserId:e,isMinimized:h&&tg(e.key),ripple:!0},n.a.createElement("i",{className:"icon-"+e.icon}),n.a.createElement("h3",{className:"chat-type"},E(e.title)),n.a.createElement(_t.a,{label:"",checked:c.includes(e.key),round:!0}))})),n.a.createElement("div",{key:"divider",className:"picker-list-divider"}),n.a.createElement("h4",{key:"header2",className:"settings-item-header"},E("FilterChats"))),f&&f.length?f.map((function(e){const t=a.includes(e);return n.a.createElement(ve.a,{key:e,className:"chat-item-clickable picker-list-item chat-item",onClick:()=>p(e),ripple:!0,disabled:!t&&b},Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e}):n.a.createElement(fe.a,{chatId:e,withChatType:!0}),n.a.createElement(_t.a,{label:"",checked:t,round:!0}))})):f&&!f.length?n.a.createElement("p",{className:"no-results",key:"no-results"},"Sorry, nothing found."):n.a.createElement(he.a,{key:"loading"})))});var ea=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a,orderedPinnedIds:n}}=e;return{chatsById:t,listIds:a.active,orderedPinnedIds:n.active,archivedPinnedIds:n.archived,archivedListIds:a.archived}},(e,t)=>Object(u.l)(t,["loadMoreChats"]))(({mode:e,state:t,dispatch:a,chatsById:c,listIds:r,orderedPinnedIds:s,archivedListIds:l,archivedPinnedIds:o,loadMoreChats:i})=>{const{chatFilter:d}=t,{selectedChatIds:u,selectedChatTypes:h}=It(t,e,!0),b=Object(n.p)(()=>{const e=r?Object(m.zb)(c,r,s,"all"):void 0,t=l?Object(m.zb)(c,l,o,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[c,r,s,l,o]),p=Object(n.p)(()=>{if(b)return b.filter(e=>!d||Object(me.a)(Object(m.l)(e),d)||u.includes(e.id)).map(({id:e})=>e)},[b,d,u]),g=Object(n.m)(e=>{a({type:"setChatFilter",payload:e})},[a]),v=Object(n.m)(n=>{a("included"===e?{type:"setIncludeFilters",payload:{...t.includeFilters,includedChatIds:n}}:{type:"setExcludeFilters",payload:{...t.excludeFilters,excludedChatIds:n}})},[e,t,a]),E=Object(n.m)(t=>{const n={};t.forEach(e=>{n[e]=!0}),a("included"===e?{type:"setIncludeFilters",payload:{includedChatIds:u,...n}}:{type:"setExcludeFilters",payload:{excludedChatIds:u,...n}})},[e,u,a]);return p?n.a.createElement(Jt,{mode:e,chatIds:p,selectedIds:u,selectedChatTypes:h,filterValue:d,onSelectedIdsChange:v,onSelectedChatTypesChange:E,onFilterChange:g,onLoadMore:i}):n.a.createElement(he.a,null)}));a(261);var ta=Object(n.h)(({currentScreen:e,state:t,dispatch:a,onScreenSelect:c,onReset:r})=>{const l=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{a({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?r():"create"===t.mode?c(s.m.FoldersCreateFolder):c(s.m.FoldersEditFolder)},[t.mode,a,e,r,c]),o=Object(n.m)(()=>{a({type:"reset"}),c(s.m.FoldersCreateFolder)},[c,a]),i=Object(n.m)(e=>{a({type:"editFolder",payload:e}),c(s.m.FoldersEditFolder)},[a,c]),d=Object(n.m)(()=>{a({type:"editIncludeFilters"}),c(s.m.FoldersIncludedChats)},[a,c]),m=Object(n.m)(()=>{a({type:"editExcludeFilters"}),c(s.m.FoldersExcludedChats)},[a,c]);switch(e){case s.m.Folders:return n.a.createElement(Wt,{onCreateFolder:o,onEditFolder:i});case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:return n.a.createElement(Xt,{state:t,dispatch:a,onAddIncludedChats:d,onAddExcludedChats:m,onReset:l});case s.m.FoldersIncludedChats:return n.a.createElement(ea,{mode:"included",state:t,dispatch:a});case s.m.FoldersExcludedChats:return n.a.createElement(ea,{mode:"excluded",state:t,dispatch:a});default:return}}),aa=a(96);a(262);var na=Object(n.h)(({options:e,range:t,label:a,value:c,disabled:r,onChange:s})=>{const l=Object(n.m)(e=>{s(Number(e.currentTarget.value))},[s]),o=Object(ce.a)("RangeSlider",r&&"disabled"),i=Object(n.p)(()=>{if(e)return c/(e.length-1)*100;if(t){const e=(t.max-t.min)/(t.step||1);return(c-t.min)/e*100}return 0},[c,e,t]),[d,m,u]=Object(n.p)(()=>e?[0,e.length-1,1]:t?[t.min,t.max,t.step||1]:[0,0,0],[t,e]);return n.a.createElement("div",{className:o},a&&n.a.createElement("div",{className:"slider-top-row"},n.a.createElement("span",{className:"label"},a),t&&n.a.createElement("span",{className:"value"},c)),n.a.createElement("div",{className:"slider-main"},n.a.createElement("div",{className:"slider-fill-track",style:`width: ${i}%`}),n.a.createElement("input",{min:d,max:m,value:c,step:u,type:"range",onChange:l}),e&&n.a.createElement("div",{className:"slider-options"},e.map((e,t)=>n.a.createElement("div",{className:Object(ce.a)("slider-option no-selection",t===c&&"active"),onClick:()=>s(t)},e)))))}),ca=a(117),ra=a(104),sa=a(44);var la=Object(n.h)(({size:e=l.xb,stickerSet:t,observeIntersection:a})=>{const c=Object(n.q)(null),s=Object(aa.b)(c,a),o="stickerSet"+t.id,i=Object(v.a)(o,!s,r.ApiMediaFormat.Lottie),{shouldRenderFullMedia:d,transitionClassNames:m}=Object(ra.a)(i,"slow");return n.a.createElement("div",{ref:c,className:"sticker-set-cover"},!d&&Object(sa.c)(t.title,2),d&&i&&n.a.createElement(Vt.a,{id:o,size:e,animationData:i,className:m}))});var oa=Object(n.h)(({stickerSet:e,observeIntersection:t})=>{const a=Object(n.q)(null),c=Object(aa.b)(a,t),r=Object(v.a)(e.hasThumbnail&&"stickerSet"+e.id,!c),{shouldRenderFullMedia:s,transitionClassNames:l}=Object(ra.a)(r,"slow");return n.a.createElement("div",{ref:a,className:"sticker-set-cover"},!s&&Object(sa.c)(e.title,2),s&&n.a.createElement("img",{src:r,className:l,alt:""}))});a(263);var ia=Object(n.h)(({sticker:e,size:t,observeIntersection:a,noAnimate:c,title:s,className:l,onClick:o,clickArg:i,onUnfaveClick:d})=>{const m=Object(n.q)(null),{isAnimated:u}=e,h="sticker"+e.id,b="sticker-button-"+e.id,p=Object(aa.b)(m,a),g=e.thumbnail?e.thumbnail.dataUri:void 0,E=Object(v.a)(h+"?size=m",!p,r.ApiMediaFormat.BlobUrl),f=p&&!c,O=Object(v.a)(h,!f,r.ApiMediaFormat.Lottie),[j,C,y]=Object(Ae.a)(Boolean(O)),k=j&&f,{shouldRenderThumb:N,shouldRenderFullMedia:I,transitionClassNames:S}=Object(ra.a)(E||k,"slow");Object(n.n)(()=>{f||y()},[y,f]);const w=Object(ce.a)("StickerButton",u&&"animated",b,l),P=N&&g?`background-image: url('${g}');`:"";return n.a.createElement("div",{ref:m,className:w,title:s||e&&e.emoji,style:P,"data-sticker-id":e.id,onClick:function(){o&&o(i)}},I&&!k&&n.a.createElement("img",{src:E,className:S}),f&&O&&n.a.createElement(Vt.a,{id:h,animationData:O,play:!0,size:t,isLowPriority:!0,onLoad:C}),d&&n.a.createElement(B.a,{className:"sticker-unfave-button",color:"dark",round:!0,onClick:function(t){t.stopPropagation(),t.preventDefault(),d(e)}},n.a.createElement("i",{className:"icon-close"})))});a(264);var da=Object(n.h)(({stickerSet:e,observeIntersection:t,onClick:a})=>{const c=Object(F.a)();if(!e||!e.stickers)return;const r=e.stickers&&e.stickers[0];return e.hasThumbnail||!r?n.a.createElement(ve.a,{narrow:!0,className:"SettingsStickerSet",inactive:!r,onClick:()=>r&&a(r)},n.a.createElement(B.a,{ariaLabel:e.title,color:"translucent"},e.isAnimated?n.a.createElement(la,{size:l.sb,stickerSet:e,observeIntersection:t}):n.a.createElement(oa,{stickerSet:e,observeIntersection:t})),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i")))):n.a.createElement(ve.a,{narrow:!0,className:"SettingsStickerSet",onClick:()=>a(r)},n.a.createElement(ia,{sticker:r,size:l.sb,title:e.title,observeIntersection:t}),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i"))))}),ma=a(153);const ua=o.k?void 0:[{value:"enter",label:"Send by Enter",subLabel:"New line by Shift + Enter"},{value:"ctrl-enter",label:`Send by ${o.e?"Cmd":"Ctrl"} + Enter`,subLabel:"New line by Enter"}],ha=["Solid and Steady","Nice and Fast","Lots of Stuff"];var ba=Object(n.h)(Object(c.h)(e=>({...Object(u.l)(e.settings.byKey,["messageTextSize","animationLevel","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers"]),stickerSetIds:e.stickers.added.setIds,stickerSetsById:e.stickers.setsById}),(e,t)=>Object(u.l)(t,["setSettingOption","loadStickerSets","loadAddedStickers"]))(({onScreenSelect:e,stickerSetIds:t,stickerSetsById:a,messageTextSize:c,animationLevel:r,messageSendKeyCombo:l,shouldAutoDownloadMediaFromContacts:o,shouldAutoDownloadMediaInPrivateChats:i,shouldAutoDownloadMediaInGroups:d,shouldAutoDownloadMediaInChannels:m,shouldAutoPlayGifs:u,shouldAutoPlayVideos:h,shouldSuggestStickers:b,shouldLoopStickers:p,setSettingOption:g,loadStickerSets:v,loadAddedStickers:E})=>{const f=Object(n.q)(null),{observe:O}=Object(aa.a)({rootRef:f}),[j,C,y]=Object(Ae.a)(),[k,N]=Object(n.r)();Object(n.n)(()=>{v()},[v]),Object(n.n)(()=>{t&&t.length&&E()},[t,E]);const I=Object(n.m)(e=>{ha.forEach((t,a)=>{document.body.classList.toggle("animation-level-"+a,e===a)}),g({animationLevel:e})},[g]),S=Object(n.m)(e=>{document.documentElement.style.setProperty("--message-text-size",e+"px"),g({messageTextSize:e})},[g]),w=Object(n.m)(e=>{N(e),C()},[C]),P=Object(F.a)(),M=t&&t.map(e=>!!(a&&a[e]&&a[e].installedDate)&&a[e]).filter(Boolean);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header"},P("SETTINGS")),n.a.createElement(na,{label:P("TextSize"),range:{min:12,max:20},value:c,onChange:S}),n.a.createElement(ve.a,{icon:"photo",onClick:()=>e(s.m.GeneralChatBackground)},P("ChatBackground"))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},"Animation Level"),n.a.createElement("p",{className:"settings-item-description"},"Choose the desired animations amount."),n.a.createElement(na,{options:ha,value:r,onChange:I})),ua&&n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("Keyboard")),n.a.createElement(ca.a,{name:"keyboard-send-settings",options:ua,onChange:e=>g({messageSendKeyCombo:e}),selected:l})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AutoDownloadMedia")),n.a.createElement(_t.a,{label:P("Contacts"),checked:o,onCheck:e=>g({shouldAutoDownloadMediaFromContacts:e})}),n.a.createElement(_t.a,{label:P("AutodownloadPrivateChats"),checked:i,onCheck:e=>g({shouldAutoDownloadMediaInPrivateChats:e})}),n.a.createElement(_t.a,{label:P("AutodownloadGroupChats"),checked:d,onCheck:e=>g({shouldAutoDownloadMediaInGroups:e})}),n.a.createElement(_t.a,{label:P("FilterChannels"),checked:m,onCheck:e=>g({shouldAutoDownloadMediaInChannels:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AutoplayMedia")),n.a.createElement(_t.a,{label:P("GifsTab2"),checked:u,onCheck:e=>g({shouldAutoPlayGifs:e})}),n.a.createElement(_t.a,{label:P("VideosTitle"),checked:h,onCheck:e=>g({shouldAutoPlayVideos:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},P("AccDescrStickers")),n.a.createElement(_t.a,{label:P("SuggestStickers"),checked:b,onCheck:e=>g({shouldSuggestStickers:e})}),n.a.createElement(_t.a,{label:P("LoopAnimatedStickers"),checked:p,onCheck:e=>g({shouldLoopStickers:e})}),n.a.createElement("div",{className:"mt-4",ref:f},M&&M.map(e=>n.a.createElement(da,{key:e.id,stickerSet:e,observeIntersection:O,onClick:w}))),k&&n.a.createElement(ma.a,{isOpen:j,fromSticker:k,onClose:y})))}));let pa;function ga(e="*",t,a=!1){pa||(pa=document.createElement("input"),pa.setAttribute("type","file")),pa.setAttribute("accept",e),a?pa.removeAttribute("multiple"):pa.setAttribute("multiple","multiple"),pa.onchange=null,pa.value="",pa.onchange=t,pa.click()}var va=a(14);function Ea(e){return[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]}function fa(e){const t=e[0].toString(16),a=e[1].toString(16),n=e[2].toString(16);return(1==t.length?"0"+t:t)+(1==a.length?"0"+a:a)+(1==n.length?"0"+n:n)}function Oa([e,t,a]){e/=255,t/=255,a/=255;let n,c,r=Math.max(e,t,a),s=Math.min(e,t,a),l=r,o=r-s;if(c=0==r?0:o/r,r==s)n=0;else{switch(r){case e:n=(t-a)/o+(t.5?Math.max(0,.65*n):Math.max(0,Math.min(1,1-.65*n)),`hsla(${360*t}, ${100*a}%, ${100*n}%, .4)`}var ya=a(13),ka=a(136);a(265);var Na=Object(n.h)(({wallpaper:e,isSelected:t,onClick:a})=>{const{slug:c,document:r}=e,o="wallpaper"+r.id,i=r.previewBlobUrl,d=Object(v.a)(o+"?size=m"),m=Object(ka.a)(r.thumbnail&&r.thumbnail.dataUri,Boolean(d),300),{shouldRenderThumb:u,shouldRenderFullMedia:h,transitionClassNames:b}=Object(ra.a)(d||i,"slow"),[p,g]=Object(n.r)(!1),{mediaData:f,downloadProgress:j}=Object(E.a)(o,!p),C=!1===Object(O.a)(p),{shouldRender:y,transitionClassNames:k}=Object(W.a)(p&&!f||c===s.n,void 0,C,"slow"),N=Object(n.m)(()=>{(async()=>{const e=await Object(va.e)(f);await ya.d(l.l,l.l,e),a(c)})()},[f,a,c]);Object(n.n)(()=>{f&&N()},[f,N]);const I=Object(n.m)(()=>{f?N():g(e=>!e)},[f,N]),S=Object(ce.a)("WallpaperTile",t&&"selected");return n.a.createElement("div",{className:S,onClick:I},n.a.createElement("div",{className:"media-inner"},u&&n.a.createElement("img",{src:m,className:"thumbnail",alt:""}),h&&n.a.createElement("img",{src:d||i,className:"full-media "+b,alt:""}),y&&n.a.createElement("div",{className:Object(ce.a)("spinner-container",k)},n.a.createElement($.a,{progress:j,onClick:I}))))});a(266);const Ia=Object(V.g)(e=>e(),6e4,!0);var Sa=Object(n.h)(Object(c.h)(e=>{const{isBackgroundBlurred:t,customBackground:a}=e.settings.byKey,{loadedWallpapers:n}=e.settings;return{customBackground:a,isBackgroundBlurred:t,loadedWallpapers:n}},(e,t)=>Object(u.l)(t,["setSettingOption","loadWallpapers","uploadWallpaper"]))(({onScreenSelect:e,customBackground:t,isBackgroundBlurred:a,loadedWallpapers:c,setSettingOption:r,loadWallpapers:o,uploadWallpaper:i})=>{Object(n.n)(()=>{Ia(()=>{o()})},[o]);const d=Object(n.m)(e=>{const{files:t}=e.target;t&&t.length>0&&i(t[0])},[i]),m=Object(n.m)(()=>{ga("image/jpeg",d,!0)},[d]),u=Object(n.m)(()=>{e(s.m.GeneralChatBackgroundColor)},[e]),h=Object(n.m)(()=>{r({customBackground:void 0,patternColor:l.s})},[r]),b=Object(n.m)(e=>{r({customBackground:e});const t=c&&c.find(t=>t.slug===e);t&&t.document.thumbnail&&async function(e){const t=[0,0,0];let a,n,c,r,s=-4,l=[0,0,0],o=0;const i=document.createElement("canvas"),d=i.getContext&&i.getContext("2d");if(!d)return t;const m=await Object(va.g)(e);c=m.naturalHeight||m.offsetHeight||m.height,n=m.naturalWidth||m.offsetWidth||m.width,i.height=c,i.width=n,d.drawImage(m,0,0);try{a=d.getImageData(0,0,n,c)}catch(e){return t}for(r=a.data.length;(s+=20){r({patternColor:Ca(e)})})},[c,r]),p=Object(n.m)(e=>{r({isBackgroundBlurred:e.target.checked})},[r]),g=Object(F.a)(),v=c&&c[0]&&c[0].slug===s.n;return n.a.createElement("div",{className:"SettingsGeneralBackground settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(ve.a,{icon:"camera-add",className:"mb-0",disabled:v,onClick:m},g("UploadImage")),n.a.createElement(ve.a,{icon:"colorize",className:"mb-0",onClick:u},g("SetColor")),n.a.createElement(ve.a,{icon:"favorite",onClick:h},g("ThemeResetToDefaults")),n.a.createElement(_t.a,{label:g("BackgroundBlurred"),checked:Boolean(a),onChange:p})),c?n.a.createElement("div",{className:"settings-wallpapers"},c.map(e=>n.a.createElement(Na,{wallpaper:e,isSelected:t===e.slug,onClick:b}))):n.a.createElement(he.a,null))}));a(267);const wa=Oa(Ea("e6ebee")),Pa=["#e6ebee","#b2cee1","#008dd0","#c6e7cb","#c4e1a6","#60b16e","#ccd0af","#a6a997","#7a7072","#fdd7af","#fdb76e","#dd8851"];function Ma(e,t){return{colorPosition:[Math.round(e[1]*(t.colorRect.width-1)),Math.round((1-e[2])*(t.colorRect.height-1))],huePosition:Math.round(e[0]*(t.hueRect.width-1))}}function Fa({colorPosition:e,huePosition:t},a){return[t/(a.hueRect.width-1),e[0]/(a.colorRect.width-1),1-e[1]/(a.colorRect.height-1)]}var La=Object(n.h)(Object(c.h)(e=>({customBackground:e.settings.byKey.customBackground}),(e,t)=>Object(u.l)(t,["setSettingOption"]))(({customBackground:e,setSettingOption:t})=>{const a=Object(n.q)(null),c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(!0),[l,o]=Object(n.r)(function(e){return e&&e.startsWith("#")?Oa(Ea(e.replace("#",""))):wa}(e)),i=Object(n.q)(l);Object(n.n)(()=>{i.current=l},[l]);const[d,m,b]=Object(Ae.a)(),[p,g]=Object(n.r)(""),[v,E]=Object(n.r)(""),f=Object(n.q)(),O=Object(n.q)();Object(n.n)(()=>{const e={offsetLeft:c.current.offsetLeft,...Object(u.l)(c.current.getBoundingClientRect(),["top","width","height"])},t={offsetLeft:r.current.offsetLeft,...Object(u.l)(r.current.getBoundingClientRect(),["width"])};function n(t){const n=[Math.min(Math.max(0,t.pageX-e.offsetLeft),e.width-1),Math.min(Math.max(0,t.pageY-e.top+a.current.scrollTop),e.height-1)],{huePosition:c}=Ma(i.current,f.current);o(Fa({colorPosition:n,huePosition:c},f.current)),m()}function s(e){const{colorPosition:a}=Ma(i.current,f.current),n=Math.min(Math.max(0,e.pageX-t.offsetLeft),t.width-1);o(Fa({colorPosition:a,huePosition:n},f.current)),m()}f.current={colorRect:e,hueRect:t},Object(h.b)(c.current,{onCapture:n,onDrag:n,onRelease:b,onClick:b,withCursor:!0}),Object(h.b)(r.current,{onCapture:s,onDrag:s,onRelease:b,onClick:b,withCursor:!0})},[m,b]);const{colorPosition:j=[0,0],huePosition:C=0}=f.current?Ma(l,f.current):{},y=fa(ja(l)),k=l[0],N=fa(ja([k,1,1]));Object(n.n)(()=>{const e=ja(l),a="#"+fa(e);g(e.join(", ")),E(a),s.current||t({customBackground:a,patternColor:Ca(e)}),s.current=!1},[l,t]),Object(n.n)(()=>{!function(e,t,a,n){let c,r,s;a.current&&n.current?(c=n.current.colorRect.width,r=n.current.colorRect.height,s=a.current):(c=e.offsetWidth,r=e.offsetHeight,s=e.getContext("2d"),e.width=c,e.height=r,a.current=s);const l=s.createImageData(c,r),o=l.data,i=ja([t,1,1]);let d=0;for(let e=0;e{!function(e){const t=e.offsetWidth;e.width=t,e.height=1;const a=e.getContext("2d"),n=a.createImageData(t,1),c=n.data;let r=0;for(let e=0;e{const t=e.currentTarget.value.replace(/[^\d, ]/g,"").slice(0,13);if(t.match(/^\d{1,3},\s?\d{1,3},\s?\d{1,3}$/)){const e=t.split(",").map(e=>Number(e.trim()));o(Oa(e))}e.currentTarget.value=t},[]),S=Object(n.m)(e=>{const t=e.currentTarget.value.replace(/[^0-9a-fA-F]/g,"").slice(0,6);t.match(/^#?[0-9a-fA-F]{6}$/)&&o(Oa(Ea(t.replace("#","")))),e.currentTarget.value=t},[]),w=Object(n.m)(e=>{o(Oa(Ea(e.currentTarget.dataset.color.replace("#",""))))},[]),P=Object(ce.a)("SettingsGeneralBackgroundColor settings-content custom-scroll",d&&"is-dragging");return n.a.createElement("div",{ref:a,className:P},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("div",{ref:c,className:"color-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translate(${j[0]}px, ${j[1]}px); background-color: #${y};`})),n.a.createElement("div",{ref:r,className:"hue-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translateX(${C}px); background-color: #${N};`})),n.a.createElement("div",{className:"tools"},n.a.createElement(pe.a,{value:v,label:"HEX",onChange:S}),n.a.createElement(pe.a,{value:p,label:"RGB",onChange:I}))),n.a.createElement("div",{className:"predefined-colors"},Pa.map(e=>n.a.createElement("div",{className:e==="#"+y?"active":void 0,"data-color":e,style:`background-color: ${e};`,onClick:w}))))}));var Aa=Object(n.h)(Object(c.h)(e=>({hasPrivateChatsNotifications:Boolean(e.settings.byKey.hasPrivateChatsNotifications),hasPrivateChatsMessagePreview:Boolean(e.settings.byKey.hasPrivateChatsMessagePreview),hasGroupNotifications:Boolean(e.settings.byKey.hasGroupNotifications),hasGroupMessagePreview:Boolean(e.settings.byKey.hasGroupMessagePreview),hasBroadcastNotifications:Boolean(e.settings.byKey.hasBroadcastNotifications),hasBroadcastMessagePreview:Boolean(e.settings.byKey.hasBroadcastMessagePreview),hasContactJoinedNotifications:Boolean(e.settings.byKey.hasContactJoinedNotifications)}),(e,t)=>Object(u.l)(t,["loadNotificationsSettings","updateContactSignUpNotification","updateNotificationSettings"]))(({hasPrivateChatsNotifications:e,hasPrivateChatsMessagePreview:t,hasGroupNotifications:a,hasGroupMessagePreview:c,hasBroadcastNotifications:r,hasBroadcastMessagePreview:s,hasContactJoinedNotifications:l,loadNotificationsSettings:o,updateContactSignUpNotification:i,updateNotificationSettings:d})=>{Object(n.n)(()=>{o()},[o]);const m=Object(n.m)((n,l,o)=>{const i="contact"===l?!e:!("group"===l?a:r),m="contact"===l?t:"group"===l?c:s;d({peerType:l,..."silent"===o&&{isSilent:!n.target.checked,isShowPreviews:m},..."showPreviews"===o&&{isShowPreviews:n.target.checked,isSilent:i}})},[s,r,c,a,t,e,d]),u=Object(n.m)(e=>{i({isSilent:!e.target.checked})},[i]),h=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("AutodownloadPrivateChats")),n.a.createElement(_t.a,{label:h("NotificationsForPrivateChats"),subLabel:h(e?"NotificationsEnabled":"NotificationsDisabled"),checked:e,onChange:e=>{m(e,"contact","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(t?"PreviewEnabled":"PreviewDisabled"),checked:t,onChange:e=>{m(e,"contact","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("FilterGroups")),n.a.createElement(_t.a,{label:h("NotificationsForGroups"),subLabel:h(a?"NotificationsEnabled":"NotificationsDisabled"),checked:a,onChange:e=>{m(e,"group","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(c?"PreviewEnabled":"PreviewDisabled"),checked:c,onChange:e=>{m(e,"group","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("FilterChannels")),n.a.createElement(_t.a,{label:h("NotificationsForChannels"),subLabel:h(r?"NotificationsEnabled":"NotificationsDisabled"),checked:r,onChange:e=>{m(e,"broadcast","silent")}}),n.a.createElement(_t.a,{label:h("MessagePreview"),subLabel:h(s?"PreviewEnabled":"PreviewDisabled"),checked:s,onChange:e=>{m(e,"broadcast","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},h("PhoneOther")),n.a.createElement(_t.a,{label:h("ContactJoined"),checked:l,onChange:u})))}));var Ta=Object(n.h)(Object(c.h)(e=>{const{settings:{byKey:{hasPassword:t},privacy:a},blocked:n,activeSessions:c}=e;return{hasPassword:t,blockedCount:n.totalCount,sessionsCount:c.length,visibilityPrivacyPhoneNumber:a.phoneNumber&&a.phoneNumber.visibility,visibilityPrivacyLastSeen:a.lastSeen&&a.lastSeen.visibility,visibilityPrivacyProfilePhoto:a.profilePhoto&&a.profilePhoto.visibility,visibilityPrivacyForwarding:a.forwards&&a.forwards.visibility,visibilityPrivacyGroupChats:a.chatInvite&&a.chatInvite.visibility}},(e,t)=>Object(u.l)(t,["loadBlockedContacts","loadAuthorizations","loadPrivacySettings"]))(({onScreenSelect:e,hasPassword:t,blockedCount:a,sessionsCount:c,visibilityPrivacyPhoneNumber:r,visibilityPrivacyLastSeen:l,visibilityPrivacyProfilePhoto:o,visibilityPrivacyForwarding:i,visibilityPrivacyGroupChats:d,loadPrivacySettings:m,loadBlockedContacts:u,loadAuthorizations:h})=>{Object(n.n)(()=>{u(),h(),m()},[u,h,m]);const b=Object(F.a)();function p(e){switch(e){case"everybody":return b("P2PEverybody");case"contacts":return b("P2PContacts");case"nobody":return b("P2PNobody")}}return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(ve.a,{icon:"delete-user",narrow:!0,onClick:()=>e(s.m.PrivacyBlockedUsers)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("BlockedUsers")),a>0&&n.a.createElement("span",{className:"subtitle"},b("Users",a)))),n.a.createElement(ve.a,{icon:"lock",narrow:!0,onClick:()=>e(t?s.m.TwoFaEnabled:s.m.TwoFaDisabled)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("TwoStepVerification")),n.a.createElement("span",{className:"subtitle"},b(t?"PasswordOn":"PasswordOff")))),n.a.createElement(ve.a,{icon:"active-sessions",narrow:!0,onClick:()=>e(s.m.PrivacyActiveSessions)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("SessionsTitle")),c>0&&n.a.createElement("span",{className:"subtitle"},1===c?"1 session":c+" sessions")))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},b("PrivacyTitle")),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyPhoneNumber)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyPhoneTitle")),n.a.createElement("span",{className:"subtitle"},p(r)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyLastSeen)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("LastSeenTitle")),n.a.createElement("span",{className:"subtitle"},p(l)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyProfilePhoto)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyProfilePhotoTitle")),n.a.createElement("span",{className:"subtitle"},p(o)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyForwarding)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyForwardsTitle")),n.a.createElement("span",{className:"subtitle"},p(i)))),n.a.createElement(ve.a,{narrow:!0,onClick:()=>e(s.m.PrivacyGroupChats)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("WhoCanAddMe")),n.a.createElement("span",{className:"subtitle"},p(d))))))}));var Ba=Object(n.h)(Object(c.h)(e=>({languages:e.settings.byKey.languages,language:e.settings.byKey.language}),(e,t)=>Object(u.l)(t,["loadLanguages","setSettingOption"]))(({languages:e,language:t,loadLanguages:a,setSettingOption:c})=>{const[r,s]=Object(n.r)(t),[l,o,i]=Object(Ae.a)();Object(n.n)(()=>{a()},[a]);const d=Object(n.m)(e=>{s(e),o(),Object(Xe.c)(e,()=>{i(),c({language:e})})},[o,i,c]),m=Object(n.p)(()=>e?function(e){return e.map(({langCode:e,nativeName:t,name:a})=>({value:e,label:t,subLabel:a}))}(e):void 0,[e]);return n.a.createElement("div",{className:"settings-content settings-item settings-language custom-scroll"},m?n.a.createElement(ca.a,{name:"keyboard-send-settings",options:m,selected:r,loadingOption:l?r:void 0,onChange:d}):n.a.createElement(he.a,null))}));function Da(e){switch(e){case s.m.PrivacyPhoneNumber:case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return"phoneNumber";case s.m.PrivacyLastSeen:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return"lastSeen";case s.m.PrivacyProfilePhoto:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return"profilePhoto";case s.m.PrivacyForwarding:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return"forwards";case s.m.PrivacyGroupChats:case s.m.PrivacyGroupChatsAllowedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return"chatInvite"}}var xa=Object(n.h)(Object(c.h)((e,{screen:t})=>{let a;const{chats:{byId:n},settings:{privacy:c}}=e;switch(t){case s.m.PrivacyPhoneNumber:a=c.phoneNumber;break;case s.m.PrivacyLastSeen:a=c.lastSeen;break;case s.m.PrivacyProfilePhoto:a=c.profilePhoto;break;case s.m.PrivacyForwarding:a=c.forwards;break;case s.m.PrivacyGroupChats:a=c.chatInvite}return a?{...a,chatsById:n}:{}},(e,t)=>Object(u.l)(t,["setPrivacyVisibility"]))(({screen:e,onScreenSelect:t,visibility:a,allowUserIds:c,allowChatIds:r,blockUserIds:l,blockChatIds:o,chatsById:i,setPrivacyVisibility:d})=>{const m=Object(F.a)(),u=Object(n.p)(()=>{switch(e){case s.m.PrivacyProfilePhoto:case s.m.PrivacyGroupChats:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")}];default:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")},{value:"nobody",label:m("P2PNobody")}]}},[m,e]),h={shouldShowDenied:"nobody"!==a,shouldShowAllowed:"everybody"!==a},b=Da(e),p=Object(n.p)(()=>{switch(e){case s.m.PrivacyPhoneNumber:return m("PrivacyPhoneTitle");case s.m.PrivacyLastSeen:return m("LastSeenTitle");case s.m.PrivacyProfilePhoto:return m("PrivacyProfilePhotoTitle");case s.m.PrivacyForwarding:return m("PrivacyForwardsTitle");case s.m.PrivacyGroupChats:return m("WhoCanAddMe");default:return}},[m,e]),g=Object(n.p)(()=>{switch(e){case s.m.PrivacyLastSeen:return m("CustomHelp");default:return}},[m,e]),v=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberAllowedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenAllowedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoAllowedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingAllowedContacts;default:return s.m.PrivacyGroupChatsAllowedContacts}})(),E=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberDeniedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenDeniedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoDeniedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingDeniedContacts;default:return s.m.PrivacyGroupChatsDeniedContacts}})(),f=Object(n.p)(()=>c&&r&&i?r.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),c.length):0,[r,c,i]),O=Object(n.p)(()=>l&&o&&i?o.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),l.length):0,[o,l,i]),j=Object(n.m)(e=>{d({privacyKey:b,visibility:e})},[b,d]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header"},p),n.a.createElement(ca.a,{name:"visibility-"+b,options:u,onChange:j,selected:a}),g&&n.a.createElement("p",{className:"settings-item-description-larger"},g)),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},m("PrivacyExceptions")),h.shouldShowAllowed&&n.a.createElement(ve.a,{narrow:!0,icon:"add-user",onClick:()=>{t(v)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},f>0&&n.a.createElement("span",{className:"date"},"+",f),n.a.createElement("span",{className:"title"},m("AlwaysShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers")))),h.shouldShowDenied&&n.a.createElement(ve.a,{narrow:!0,icon:"delete-user",onClick:()=>{t(E)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},O>0&&n.a.createElement("span",{className:"date"},"−",O),n.a.createElement("span",{className:"title"},m("NeverShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers"))))))}));function Ua(e){return[e.region,e.country].filter(Boolean).join(", ")}function Ra(e){return`${e.deviceModel}${e.deviceModel?", ":""} ${e.platform} ${e.systemVersion}`}var Ga=Object(n.h)(Object(c.h)(e=>({activeSessions:e.activeSessions}),(e,t)=>Object(u.l)(t,["loadAuthorizations","terminateAuthorization","terminateAllAuthorizations"]))(({activeSessions:e,loadAuthorizations:t,terminateAuthorization:a,terminateAllAuthorizations:c})=>{const[r,s,l]=Object(Ae.a)();Object(n.n)(()=>{t()},[t]);const o=Object(n.m)(e=>{a({hash:e})},[a]),i=Object(n.m)(()=>{l(),c()},[l,c]),d=Object(n.p)(()=>e.find(e=>e.isCurrent),[e]),m=Object(n.p)(()=>e.filter(e=>!e.isCurrent),[e]),u=Object(F.a)();function h(e){return n.a.createElement(ve.a,{key:e.hash,ripple:!0,narrow:!0,contextActions:[{title:"Terminate",icon:"stop",handler:()=>{o(e.hash)}}]},n.a.createElement("div",{className:"multiline-menu-item full-size"},n.a.createElement("span",{className:"date"},Object(D.g)(1e3*e.dateActive)),n.a.createElement("span",{className:"title"},e.appName),n.a.createElement("span",{className:"subtitle black tight"},Ra(e)),n.a.createElement("span",{className:"subtitle"},e.ip," - ",Ua(e))))}return n.a.createElement("div",{className:"settings-content custom-scroll"},d&&(p=d,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},u("AuthSessions.CurrentSession")),n.a.createElement(ve.a,{narrow:!0,inactive:!0},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},p.appName),n.a.createElement("span",{className:"subtitle black tight"},Ra(p)),n.a.createElement("span",{className:"subtitle"},p.ip," - ",Ua(p)))),n.a.createElement(ve.a,{className:"destructive mb-0",icon:"stop",ripple:!0,narrow:!0,onClick:s},u("TerminateAllSessions")))),m&&(b=m,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4"},"Other Sessions"),b.map(h))),m&&n.a.createElement(Lt.a,{isOpen:r,onClose:l,text:"Are you sure you want to terminate all other sessions?",confirmLabel:"Terminate All Other Sessions",confirmHandler:i,confirmIsDestructive:!0}),";");var b,p}));var za=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a},blocked:{ids:n}}=e;return{chatsByIds:t,usersByIds:a,blockedIds:n}},(e,t)=>Object(u.l)(t,["unblockContact"]))(({chatsByIds:e,usersByIds:t,blockedIds:a,unblockContact:c})=>{const r=Object(n.m)(e=>{c({contactId:e})},[c]),s=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content infinite-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("p",{className:"settings-item-description-larger mt-0 mb-2"},s("BlockedUsersInfo"))),n.a.createElement("div",{className:"chat-list custom-scroll"},a&&a.length?n.a.createElement("div",{className:"scroll-container"},a.map((a,c)=>function(a,c,s){const o=Object(m.kb)(a),i=o?t[a]:void 0,d=o?void 0:e[a],u=Object(ce.a)("Chat chat-item-clickable blocked-list-item",o?"private":"group");return n.a.createElement(ve.a,{key:a,className:u,ripple:!0,narrow:!0,contextActions:[{title:"Unblock",icon:"unlock",handler:()=>{r(a)}}],style:`top: ${(s+c)*l.h}px;`},n.a.createElement(U.a,{size:"medium",user:i,chat:d}),n.a.createElement("div",{className:"contact-info"},n.a.createElement("h3",null,Object(x.a)((o?Object(m.Y)(i):Object(m.l)(d))||"")),i&&i.phoneNumber&&n.a.createElement("div",{className:"contact-phone"},Object(Tt.c)(i.phoneNumber)),i&&!i.phoneNumber&&i.username&&n.a.createElement("div",{className:"contact-username"},"@",i.username)))}(a,c,0))):a&&!a.length?n.a.createElement("div",{className:"no-results"},"List is empty"):n.a.createElement(he.a,{key:"loading"}))),n.a.createElement(xt,{isShown:!0,onClick:()=>{},className:"not-implemented",ariaLabel:"Add a blocked user"},n.a.createElement("i",{className:"icon-add"})))})),qa=a(119);var $a=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},Object(x.a)(a("EnabledPasswordText"),["br"]))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(ve.a,{icon:"edit",onClick:()=>t(s.m.TwoFaChangePasswordCurrent)},a("ChangePassword")),n.a.createElement(ve.a,{icon:"password-off",onClick:()=>t(s.m.TwoFaTurnOff)},a("TurnPasswordOff")),n.a.createElement(ve.a,{icon:"email",onClick:()=>t(s.m.TwoFaRecoveryEmailCurrentPassword)},a("SetRecoveryEmail"))))})),Ha=a(138),Va=a(139);var Ya=Object(n.h)(({error:e,isLoading:t,expectedPassword:a,placeholder:c="Current Password",hint:r,submitLabel:s,clearError:l,onSubmit:o})=>{const[i,d]=Object(n.r)(""),[m,u]=Object(n.r)(!1),h=Object(n.m)(e=>{a&&e!==a?d("Passwords Should Be Equal"):o(e)},[o,a]),b=Object(n.m)(()=>{l&&l(),d("")},[l]),p=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Ha.a,{isBig:!0,isPasswordVisible:m})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Va.a,{error:i||e,hint:r,placeholder:c,submitLabel:s||p("Next"),clearError:b,isLoading:t,isPasswordVisible:m,onChangePasswordVisibility:u,onSubmit:h})))});var Wa=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onStart:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},a("SetAdditionalPasswordInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(B.a,{onClick:t},a("EditAdminTransferSetPassword"))))}));const Ka=o.f?550:400;var Qa=Object(n.h)(Object(c.h)((e,{icon:t})=>({animatedEmoji:Object(d.c)(e,"email"===t?"💌":"💡")}))(({animatedEmoji:e,type:t="text",isLoading:a,error:c,placeholder:r,shouldConfirm:s,clearError:l,onSubmit:i})=>{const d=Object(n.q)(null),[m,u]=Object(n.r)(""),[h,b,p]=Object(Ae.a)(!1);Object(n.n)(()=>{o.k||setTimeout(()=>{d.current.focus()},Ka)},[]);const g=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement("form",{action:"",onSubmit:e=>{e.preventDefault(),d.current&&i(m)}},n.a.createElement(pe.a,{ref:d,value:m,inputMode:t,label:r,error:c,onChange:e=>{c&&l&&l(),u(e.target.value)}}),m?n.a.createElement(B.a,{type:"submit",isLoading:a,ripple:!0},g("Continue")):n.a.createElement(B.a,{isText:!0,isLoading:a,ripple:!0,onClick:s?b:()=>{i()}},g("YourEmailSkip"))),s&&n.a.createElement(be.a,{className:"narrow",isOpen:h,title:g("YourEmailSkipWarning"),onClose:p},Object(x.a)(g("YourEmailSkipWarningText"),["br","simple_markdown"]),n.a.createElement("div",{className:"dialog-buttons"},n.a.createElement(B.a,{color:"danger",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:()=>{p(),i()}},g("YourEmailSkip")),n.a.createElement(B.a,{color:"primary",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:p},g("Cancel"))))))}));var Za=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🥳")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3"},a("TwoStepVerificationPasswordSetInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(B.a,{onClick:()=>{t(s.m.Privacy)}},a("TwoStepVerificationPasswordReturnSettings"))))}));const Xa=o.f?550:400;var _a=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"💌"),codeLength:e.twoFaSettings.waitingEmailCodeLength}))(({animatedEmoji:e,codeLength:t,isLoading:a,error:c,clearError:r,onSubmit:s})=>{const l=Object(n.q)(null),[i,d]=Object(n.r)("");Object(n.n)(()=>{o.k||setTimeout(()=>{l.current.focus()},Xa)},[]);const m=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(qa.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(pe.a,{value:i,ref:l,inputMode:"decimal",label:m("YourEmailCode"),error:c,onChange:e=>{c&&r&&r();const a=e.target.value.slice(0,t);a.length===t&&s(a),d(a),e.target.value=a}}),a&&n.a.createElement(he.a,null)))}));var Ja=Object(n.h)(Object(c.h)(e=>({...e.twoFaSettings}),(e,t)=>Object(u.l)(t,["updatePassword","updateRecoveryEmail","clearPassword","provideTwoFaEmailCode","checkPassword","clearTwoFaError"]))(({currentScreen:e,state:t,hint:a,isLoading:c,error:r,waitingEmailCodeLength:l,dispatch:o,onScreenSelect:i,updatePassword:d,checkPassword:m,clearTwoFaError:u,updateRecoveryEmail:h,provideTwoFaEmailCode:b,clearPassword:p})=>{Object(n.n)(()=>{l&&(e===s.m.TwoFaNewPasswordEmail?i(s.m.TwoFaNewPasswordEmailCode):e===s.m.TwoFaRecoveryEmail&&i(s.m.TwoFaRecoveryEmailCode))},[e,i,l]);const g=Object(n.m)(()=>{o({type:"reset"}),i(s.m.TwoFaNewPassword)},[o,i]),v=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaNewPasswordConfirm)},[o,i]),E=Object(n.m)(()=>{i(s.m.TwoFaNewPasswordHint)},[i]),f=Object(n.m)(e=>{o({type:"setHint",payload:e}),i(s.m.TwoFaNewPasswordEmail)},[o,i]),O=Object(n.m)(e=>{o({type:"setEmail",payload:e}),d({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),j=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaChangePasswordNew)}})},[m,o,i]),C=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaChangePasswordConfirm)},[o,i]),y=Object(n.m)(()=>{i(s.m.TwoFaChangePasswordHint)},[i]),k=Object(n.m)(e=>{o({type:"setHint",payload:e}),d({...t,hint:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),N=Object(n.m)(e=>{p({currentPassword:e,onSuccess:()=>{i(s.m.Privacy)}})},[p,i]),I=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaRecoveryEmail)}})},[m,o,i]),S=Object(n.m)(e=>{o({type:"setEmail",payload:e}),h({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,h]),w=Object(n.m)(e=>{b({code:e})},[b]),P=Object(F.a)();switch(e){case s.m.TwoFaDisabled:return n.a.createElement(Wa,{onStart:g});case s.m.TwoFaNewPassword:return n.a.createElement(Ya,{placeholder:P("EnterPassword"),submitLabel:P("Continue"),onSubmit:v});case s.m.TwoFaNewPasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),submitLabel:P("Continue"),onSubmit:E});case s.m.TwoFaNewPasswordHint:return n.a.createElement(Qa,{icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:f});case s.m.TwoFaNewPasswordEmail:return n.a.createElement(Qa,{icon:"email",type:"email",isLoading:c,error:r,clearError:u,placeholder:P("RecoveryEmailTitle"),shouldConfirm:!0,onSubmit:O});case s.m.TwoFaNewPasswordEmailCode:return n.a.createElement(_a,{isLoading:c,error:r,clearError:u,onSubmit:w});case s.m.TwoFaCongratulations:return n.a.createElement(Za,{onScreenSelect:i});case s.m.TwoFaEnabled:return n.a.createElement($a,{onScreenSelect:i});case s.m.TwoFaChangePasswordCurrent:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:j});case s.m.TwoFaChangePasswordNew:return n.a.createElement(Ya,{placeholder:P("PleaseEnterNewFirstPassword"),onSubmit:C});case s.m.TwoFaChangePasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),onSubmit:y});case s.m.TwoFaChangePasswordHint:return n.a.createElement(Qa,{isLoading:c,error:r,clearError:u,icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:k});case s.m.TwoFaTurnOff:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:N});case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:I});case s.m.TwoFaRecoveryEmail:return n.a.createElement(Qa,{icon:"email",type:"email",placeholder:P("RecoveryEmailTitle"),onSubmit:S});case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(_a,{isLoading:c,error:r,clearError:u,onSubmit:w});default:return}}));var en=Object(n.h)(({itemIds:e,selectedIds:t,filterValue:a,filterPlaceholder:c,notFoundText:r,searchInputId:s,isLoading:l,onSelectedIdsChange:o,onFilterChange:i,onLoadMore:d})=>{const u=Object(n.q)(null),h=t.length>10;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{u.current.focus()})},500)},[]);const b=Object(n.m)(e=>{const a=[...t];a.includes(e)?a.splice(a.indexOf(e),1):a.push(e),o(a),i("")},[t,o,i]),p=Object(n.m)(e=>{const{value:t}=e.currentTarget;i(t)},[i]),[g,v]=Object(ue.a)(d,e,Boolean(a)),E=Object(F.a)();return n.a.createElement("div",{className:"Picker"},n.a.createElement("div",{className:"picker-header custom-scroll"},t.map((e,a)=>n.a.createElement(Ze.a,{chatOrUserId:e,isMinimized:h&&an.a.createElement(ve.a,{key:e,className:"chat-item-clickable picker-list-item",onClick:()=>b(e),ripple:!0},n.a.createElement(_t.a,{label:"",checked:t.includes(e)}),Object(m.kb)(e)?n.a.createElement(Ee.a,{userId:e}):n.a.createElement(fe.a,{chatId:e})))):l||!g||g.length?n.a.createElement(he.a,null):n.a.createElement("p",{className:"no-results"},r||"Sorry, nothing found."))});function tn(e,t){const{privacy:a}=e.settings;switch(t){case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return a.phoneNumber;case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return a.lastSeen;case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return a.profilePhoto;case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return a.forwards;case s.m.PrivacyGroupChatsDeniedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return a.chatInvite}}var an=Object(n.h)(Object(c.h)((e,{screen:t})=>{const{chats:{byId:a,listIds:n,orderedPinnedIds:c},currentUserId:r}=e;return{currentUserId:r,chatsById:a,listIds:n.active,orderedPinnedIds:c.active,archivedPinnedIds:c.archived,archivedListIds:n.archived,settings:tn(e,t)}},(e,t)=>Object(u.l)(t,["setPrivacySettings"]))(({currentUserId:e,isAllowList:t,screen:a,settings:c,chatsById:r,listIds:l,orderedPinnedIds:o,archivedListIds:i,archivedPinnedIds:d,setPrivacySettings:u,onScreenSelect:h})=>{const b=Object(n.p)(()=>c?t?[...c.allowUserIds,...c.allowChatIds]:[...c.blockUserIds,...c.blockChatIds]:[],[t,c]),[p,g]=Object(n.r)(""),[v,E]=Object(n.r)(!1),[f,O]=Object(n.r)(b),j=Object(n.p)(()=>{const e=l?Object(m.zb)(r,l,o,"all"):void 0,t=i?Object(m.zb)(r,i,d,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[r,l,o,i,d]),C=Object(n.p)(()=>{if(j)return j.filter(t=>(Object(m.kb)(t.id)&&t.id!==e||Object(m.jb)(t))&&(!p||Object(me.a)(Object(m.l)(t),p)||b.includes(t.id))).map(({id:e})=>e)},[j,e,p,b]),y=Object(n.m)(e=>{O(e),E(!0)},[]),k=Object(n.m)(()=>{u({privacyKey:Da(a),isAllowList:Boolean(t),contactsIds:f}),h(s.m.Privacy)},[t,f,h,a,u]),N=Object(F.a)();return n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(en,{itemIds:C||[],selectedIds:f,filterValue:p,filterPlaceholder:N(t?"AlwaysShareWithPlaceholder":"NeverShareWithPlaceholder"),searchInputId:"new-group-picker-search",onSelectedIdsChange:y,onFilterChange:g}),n.a.createElement(xt,{isShown:v,onClick:k,ariaLabel:N(t?"AlwaysShareWithTitle":"NeverShareWithTitle")},n.a.createElement("i",{className:"icon-arrow-right"})))}));a(268);const nn=Object.keys(s.m).length/2;var cn=Object(n.h)(({currentScreen:e,onScreenSelect:t,onReset:a})=>{const[c,r]=jt(Pt,wt),[l,i]=jt(Ft,Mt),d=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{r({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?a():"create"===c.mode?t(s.m.FoldersCreateFolder):t(s.m.FoldersEditFolder)},[c.mode,r,e,a,t]),m=Object(n.m)(()=>{r({type:"saveFilters"}),d()},[r,d]);function u(){return n.a.createElement(n.a.Fragment,null,n.a.createElement(At,{currentScreen:e,onReset:d,onSaveFilter:m,editedFolderId:c.folderId}),function(){switch(e){case s.m.Main:return n.a.createElement(Bt,{onScreenSelect:t});case s.m.EditProfile:return n.a.createElement($t,null);case s.m.General:return n.a.createElement(ba,{onScreenSelect:t});case s.m.Notifications:return n.a.createElement(Aa,null);case s.m.Privacy:return n.a.createElement(Ta,{onScreenSelect:t});case s.m.Language:return n.a.createElement(Ba,null);case s.m.GeneralChatBackground:return n.a.createElement(Sa,{onScreenSelect:t});case s.m.GeneralChatBackgroundColor:return n.a.createElement(La,{onScreenSelect:t});case s.m.PrivacyActiveSessions:return n.a.createElement(Ga,null);case s.m.PrivacyBlockedUsers:return n.a.createElement(za,null);case s.m.PrivacyPhoneNumber:case s.m.PrivacyLastSeen:case s.m.PrivacyProfilePhoto:case s.m.PrivacyForwarding:case s.m.PrivacyGroupChats:return n.a.createElement(xa,{screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement(an,{isAllowList:!0,screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement(an,{screen:e,onScreenSelect:t});case s.m.Folders:case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement(ta,{currentScreen:e,state:c,dispatch:r,onScreenSelect:t,onReset:d});case s.m.TwoFaDisabled:case s.m.TwoFaNewPassword:case s.m.TwoFaNewPasswordConfirm:case s.m.TwoFaNewPasswordHint:case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaCongratulations:case s.m.TwoFaEnabled:case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:case s.m.TwoFaChangePasswordHint:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:case s.m.TwoFaRecoveryEmail:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(Ja,{currentScreen:e,state:l,dispatch:i,onScreenSelect:t});default:return}}())}return n.a.createElement(T.a,{id:"Settings",name:o.f?"slide-layers":"push-slide",activeKey:e,renderCount:nn},u)});const rn=Object(V.g)(e=>e(),6e4,!0);var sn=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users;return{usersById:a,contactIds:t}},(e,t)=>Object(u.l)(t,["loadContactList","openChat"]))(({filter:e,usersById:t,contactIds:a,loadContactList:c,openChat:r})=>{Object(n.n)(()=>{rn(()=>{c()})});const s=Object(n.m)(e=>{r({id:e})},[r]),l=Object(n.p)(()=>{if(!a)return;const n=e?a.filter(a=>{const n=t[a];if(!n)return!1;const c=Object(m.Y)(n);return c&&Object(me.a)(c,e)}):a;return Object(m.Cb)(n,t)},[e,t,a]),[i,d]=Object(ue.a)(void 0,l,Boolean(e));return n.a.createElement(ge.a,{items:i,onLoadMore:d,className:"chat-list custom-scroll"},i&&i.length?i.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable",onClick:()=>s(e),ripple:!o.f},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0,avatarSize:"large"}))):i&&!i.length?n.a.createElement("p",{className:"no-results",key:"no-results"},e.length?"No contacts matched your search.":"Contact list is empty."):n.a.createElement(he.a,{key:"loading"}))}));const ln=Object(V.g)(e=>e(),6e4,!0);var on=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users,{byId:n}=e.chats,{currentUserId:c}=e,{query:r,fetchingStatus:s,globalResults:l,localResults:o}=e.globalSearch,{userIds:i}=l||{},{userIds:d}=o||{};return{currentUserId:c,usersById:a,chatsById:n,localContactIds:t,searchQuery:r,isSearching:s&&s.chats,globalUserIds:i,localUserIds:d}},(e,t)=>Object(u.l)(t,["loadContactList","setGlobalSearchQuery"]))(({isChannel:e,selectedMemberIds:t,onSelectedMemberIdsChange:a,onNextStep:c,onReset:r,currentUserId:s,usersById:l,chatsById:o,localContactIds:i,searchQuery:d,isSearching:h,localUserIds:b,globalUserIds:p,loadContactList:g,setGlobalSearchQuery:v})=>{Object(n.n)(()=>{ln(()=>{g()})});const E=Object(n.m)(e=>{v({query:e})},[v]),f=Object(n.p)(()=>{const e=i?Object(m.Bb)(i.filter(e=>e!==s),o):[];if(!d)return e;const a=e.filter(e=>{const t=l[e];if(!t)return!1;const a=Object(m.Y)(t);return a&&Object(me.a)(a,d)});return Object(m.Bb)(Object(u.o)([...a,...b||[],...p||[]]),o,!1,t)},[i,d,b,p,l,o,t,s]),O=Object(n.m)(()=>{t.length&&(v({query:""}),c())},[t,v,c]),j=Object(F.a)();return n.a.createElement("div",{className:"NewChat step-1"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:r,ariaLabel:"Return to Chat List"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,j("GroupAddMembers"))),n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(en,{itemIds:f,selectedIds:t,filterValue:d,filterPlaceholder:j("SendMessageTo"),searchInputId:"new-group-picker-search",isLoading:h,onSelectedIdsChange:a,onFilterChange:E}),n.a.createElement(xt,{isShown:Boolean(t.length),onClick:O,ariaLabel:e?"Continue To Channel Info":"Continue To Group Info"},n.a.createElement("i",{className:"icon-arrow-right"}))))}));var dn=Object(n.h)(Object(c.h)(e=>{const{progress:t,error:a}=e.chatCreation||{};return{creationProgress:t,creationError:a}},(e,t)=>Object(u.l)(t,["createGroupChat","createChannel"]))(({isChannel:e,memberIds:t,onReset:a,creationProgress:c,creationError:r,createGroupChat:l,createChannel:o})=>{const i=Object(F.a)(),[d,m]=Object(n.r)(""),[u,h]=Object(n.r)(""),[b,p]=Object(n.r)(),[g,v]=Object(n.r)(),E=c===s.a.InProgress,f=Object(n.m)(e=>{const{value:t}=e.currentTarget,a=t.replace(/^\s+/,"");m(a),a!==t&&(e.currentTarget.value=a)},[]),O=Object(n.m)(e=>{h(e.currentTarget.value)},[]),j=Object(n.m)(()=>{d.length?t.length>199?v("Sorry, creating supergroups is not yet supported"):l({title:d,photo:b,memberIds:t}):v("Chat title can't be empty")},[d,t,l,b,"Chat title can't be empty","Sorry, creating supergroups is not yet supported"]),C=Object(n.m)(()=>{d.length?o({title:d,about:u,photo:b,memberIds:t}):v("Channel title can't be empty")},[d,o,u,b,t,"Channel title can't be empty"]);Object(n.n)(()=>{c===s.a.Complete&&a(!0)},[c,a]);const y=r||("Chat title can't be empty"!==g&&"Channel title can't be empty"!==g?g:void 0);return n.a.createElement("div",{className:"NewChat"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>a(),ariaLabel:"Return to member selection"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,i(e?"NewChannel":"NewGroup"))),n.a.createElement("div",{className:"NewChat-inner step-2"},n.a.createElement(Dt.a,{onChange:p,title:i("AddPhoto")}),n.a.createElement(pe.a,{value:d,onChange:f,label:i(e?"EnterChannelName":"GroupName"),error:"Chat title can't be empty"===g||"Channel title can't be empty"===g?g:void 0}),e&&n.a.createElement(n.a.Fragment,null,n.a.createElement(pe.a,{value:u,onChange:O,label:i("DescriptionOptionalPlaceholder")}),n.a.createElement("p",{className:"note"},i("DescriptionInfo"))),y&&n.a.createElement("p",{className:"error"},y),n.a.createElement("h3",{className:"chat-members-heading"},i("GroupInfo.ParticipantCount",t.length,"i")),n.a.createElement("div",{className:"chat-members-list custom-scroll"},t.map(e=>n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:e}))))),n.a.createElement(xt,{isShown:0!==d.length,onClick:e?C:j,disabled:E,ariaLabel:e?i("ChannelIntro.CreateChannel"):"Create Group"},E?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-arrow-right"})))}));a(269);const mn=Object.keys(s.d).length/2;var un=Object(n.h)(({isChannel:e=!1,content:t,onContentChange:a,onReset:c})=>{const[r,l]=Object(n.r)([]),i=Object(n.m)(()=>{a(e?s.d.NewChannelStep2:s.d.NewGroupStep2)},[e,a]);return n.a.createElement(T.a,{id:"NewChat",name:o.f?"slide-layers":"push-slide",renderCount:mn,activeKey:t},()=>{switch(t){case s.d.NewChannelStep1:case s.d.NewGroupStep1:return n.a.createElement(on,{isChannel:e,selectedMemberIds:r,onSelectedMemberIdsChange:l,onNextStep:i,onReset:c});case s.d.NewChannelStep2:case s.d.NewGroupStep2:return n.a.createElement(dn,{isChannel:e,memberIds:r,onReset:c});default:return}})}),hn=a(178);a(270);var bn=Object(n.h)(({onReset:e})=>{const t=Object(F.a)();return n.a.createElement("div",{className:"ArchivedChats"},n.a.createElement("div",{className:"left-header"},n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:e,ariaLabel:"Return to chat list"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,t("ArchivedChats"))),n.a.createElement(hn.a,{folderType:"archived",noChatsText:"Archive is empty."}))});const pn={Down:!0,ArrowDown:!0,Up:!0,ArrowUp:!0,Left:!0,ArrowLeft:!0,Right:!0,ArrowRight:!0," ":!0,PageUp:!0,PageDown:!0,End:!0,Home:!0,Tab:!0},gn=e=>{e.preventDefault()};function vn(e){pn[e.key]&&gn(e)}function En(){document.addEventListener("wheel",gn,{passive:!1}),window.ontouchmove=gn,document.onkeydown=vn}function fn(){document.removeEventListener("wheel",gn),window.ontouchmove=null,document.onkeydown=null}var On=a(48),jn=a(143);function Cn(e,t){return e?"Copy Selected Text":t?"Copy Text":"Copy"}var yn=a(163),kn=a(47);a(271);var Nn=({isOpen:e,message:t,anchor:a,canSendNow:c,canReschedule:s,canReply:l,canEdit:o,canPin:i,canUnpin:d,canDelete:u,canForward:h,canFaveSticker:b,canUnfaveSticker:p,canCopy:g,canCopyLink:v,canSelect:E,onReply:f,onEdit:O,onPin:C,onUnpin:y,onForward:k,onDelete:N,onFaveSticker:I,onUnfaveSticker:S,onSelect:w,onSend:P,onReschedule:M,onClose:L,onCloseAnimationEnd:A,onCopyLink:T})=>{Object(n.n)(()=>{Object(j.b)(200)},[e]);const B=function(e,t,a){const n=[],c=Object(m.N)(e),s=Object(m.G)(e),l=Object(m.D)(e,"inline"),o=s&&l&&jn.a,i=window.getSelection();if(o&&n.push({label:"Copy Media",handler:()=>{On.b(l,r.ApiMediaFormat.BlobUrl).then(jn.b),t&&t()}}),c){const e=Boolean(i&&i.anchorNode&&i.anchorNode.parentNode&&i.anchorNode.parentNode.closest(".Message .content-inner")&&""!==i.toString().replace(/(?:\r\n|\r|\n)/g,""));n.push({label:Cn(e,o),handler:()=>{const a=e&&i?i.toString():c;Object(jn.c)(a),t&&t()}})}return a&&n.push({label:"CopyMessageLink",handler:()=>{a(),t&&t()}}),n}(t,L,v?T:void 0),D=Object(n.m)(()=>document.querySelector(`.active > .MessageList div[data-message-id="${t.id}"]`),[t.id]),x=Object(n.m)(()=>document.querySelector(".active > .MessageList"),[]),U=Object(n.m)(()=>document.querySelector(".MessageContextMenu .bubble"),[]),{positionX:R,positionY:G,style:z}=Object(yn.a)(a,D,x,U,10,document.querySelector(".MiddleHeader").offsetHeight),$=Object(F.a)();return n.a.createElement(kn.a,{isOpen:e,positionX:R,positionY:G,style:z,className:"MessageContextMenu fluid",onClose:L,onCloseAnimationEnd:A},c&&n.a.createElement(q.a,{icon:"send-outline",onClick:P},$("MessageScheduleSend")),s&&n.a.createElement(q.a,{icon:"schedule",onClick:M},$("MessageScheduleEditTime")),l&&n.a.createElement(q.a,{icon:"reply",onClick:f},$("Reply")),o&&n.a.createElement(q.a,{icon:"edit",onClick:O},$("Edit")),b&&n.a.createElement(q.a,{icon:"favorite",onClick:I},$("AddToFavorites")),p&&n.a.createElement(q.a,{icon:"favorite",onClick:S},$("Stickers.RemoveFromFavorites")),g&&B.map(e=>n.a.createElement(q.a,{key:e.label,icon:"copy",onClick:e.handler},$(e.label))),i&&n.a.createElement(q.a,{icon:"pin",onClick:C},$("DialogPin")),d&&n.a.createElement(q.a,{icon:"unpin",onClick:y},$("DialogUnpin")),h&&n.a.createElement(q.a,{icon:"forward",onClick:k},$("Forward")),E&&n.a.createElement(q.a,{icon:"select",onClick:w},$("Common.Select")),u&&n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:N},$("Delete")))};var In=Object(n.h)(Object(c.h)((e,{message:t,messageListType:a})=>{const{threadId:n}=Object(d.y)(e)||{},{noOptions:c,canReply:r,canPin:s,canUnpin:l,canDelete:o,canEdit:i,canForward:m,canFaveSticker:u,canUnfaveSticker:h,canCopy:b,canCopyLink:p,canSelect:g}=n&&Object(d.b)(e,t,n)||{},v="pinned"===a,E="scheduled"===a;return{noOptions:c,canSendNow:E,canReschedule:E,canReply:!v&&!E&&r,canPin:!E&&s,canUnpin:!E&&l,canDelete:o,canEdit:!v&&i,canForward:!E&&m,canFaveSticker:!E&&u,canUnfaveSticker:!E&&h,canCopy:b,canCopyLink:!E&&p,canSelect:g}},(e,t)=>Object(u.l)(t,["setReplyingToId","setEditingId","pinMessage","openForwardMenu","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink"]))(({isOpen:e,messageListType:t,message:a,album:c,anchor:r,onClose:s,onCloseAnimationEnd:l,noOptions:o,canSendNow:i,canReschedule:d,canReply:m,canPin:u,canUnpin:h,canDelete:b,canEdit:p,canForward:g,canFaveSticker:v,canUnfaveSticker:E,canCopy:f,canCopyLink:O,canSelect:j,setReplyingToId:C,setEditingId:y,pinMessage:k,openForwardMenu:N,faveSticker:I,unfaveSticker:S,toggleMessageSelection:w,sendScheduledMessages:P,rescheduleMessage:M,loadMessageLink:F})=>{const{transitionClassNames:L}=Object(W.a)(e,l,void 0,!1),[A,T]=Object(n.r)(!0),[B,x]=Object(n.r)(!1),[U,R]=Object(n.r)(!1),[G,z,q]=Object(Ae.a)(),$=Object(n.m)(()=>{T(!1),x(!0)},[]),H=Object(n.m)(()=>{T(!1),s()},[s]),V=Object(n.m)(()=>{x(!1),s()},[s]),Y=Object(n.m)(()=>{R(!1),s()},[s]),K=Object(n.m)(()=>{q(),s()},[q,s]),Q=Object(n.m)(()=>{C({messageId:a.id}),H()},[C,a.id,H]),Z=Object(n.m)(()=>{y({messageId:a.id}),H()},[y,a.id,H]),X=Object(n.m)(()=>{T(!1),R(!0)},[]),_=Object(n.m)(()=>{k({messageId:a.id,isUnpin:!0}),H()},[k,a.id,H]),J=Object(n.m)(()=>{if(H(),c&&c.messages){const e=c.messages.map(({id:e})=>e);N({fromChatId:a.chatId,messageIds:e})}else N({fromChatId:a.chatId,messageIds:[a.id]})},[N,a,H,c]),ee=Object(n.m)(()=>{H(),I({sticker:a.content.sticker})},[H,a.content.sticker,I]),te=Object(n.m)(()=>{H(),S({sticker:a.content.sticker})},[H,a.content.sticker,S]),ae=Object(n.m)(()=>{const e=c&&c.messages?{messageId:a.id,childMessageIds:c.messages.map(({id:e})=>e),withShift:!1}:{messageId:a.id,withShift:!1};w(e),H()},[H,a.id,w,c]),ne=Object(n.m)(()=>{P({chatId:a.chatId,id:a.id}),H()},[H,a.chatId,a.id,P]),ce=Object(n.m)(()=>{T(!1),z()},[z]),re=Object(n.m)(e=>{M({chatId:a.chatId,messageId:a.id,scheduledAt:Math.round(e.getTime()/1e3)})},[a.chatId,a.id,M]),se=Object(n.m)(()=>{F({messageId:a.id,chatId:a.chatId}),H()},[H,F,a.chatId,a.id]);if(Object(n.n)(()=>(En(),fn),[]),o)return void H();const le=new Date;return le.setFullYear(le.getFullYear()+1),n.a.createElement("div",{className:["ContextMenuContainer",L].join(" ")},n.a.createElement(Nn,{message:a,isOpen:A,anchor:r,canSendNow:i,canReschedule:d,canReply:m,canDelete:b,canPin:u,canUnpin:h,canEdit:p,canForward:g,canFaveSticker:v,canUnfaveSticker:E,canCopy:f,canCopyLink:O,canSelect:j,onReply:Q,onEdit:Z,onPin:X,onUnpin:_,onForward:J,onDelete:$,onFaveSticker:ee,onUnfaveSticker:te,onSelect:ae,onSend:ne,onReschedule:ce,onClose:H,onCopyLink:se}),n.a.createElement(Me,{isOpen:B,isSchedule:"scheduled"===t,onClose:V,album:c,message:a}),n.a.createElement(Fe,{isOpen:U,messageId:a.id,chatId:a.chatId,onClose:Y}),n.a.createElement(Pe,{isOpen:G,withTimePicker:!0,selectedAt:1e3*a.date,maxAt:Object(D.k)(le),isFutureMode:!0,onClose:K,onSubmit:re}))}));a(272);var Sn=Object(n.h)(Object(c.h)((e,{fromSticker:t})=>({stickerSet:Object(d.ub)(e,t.stickerSetId)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet","sendMessage"]))(({isOpen:e,fromSticker:t,stickerSet:a,onClose:c,loadStickers:r,toggleStickerSet:s,sendMessage:o})=>{const i=Object(n.q)(null),{observe:d}=Object(aa.a)({rootRef:i,throttleMs:200,isDisabled:!e});Object(n.n)(()=>{if(e){const{stickerSetId:e,stickerSetAccessHash:a}=t;r({stickerSetId:e,stickerSetAccessHash:a})}},[e,t,r]);const m=Object(n.m)(e=>{e={...e,isPreloadedGlobally:!0},o({sticker:e}),c()},[c,o]),u=Object(n.m)(()=>{s({stickerSetId:t.stickerSetId}),c()},[t.stickerSetId,c,s]);return n.a.createElement(be.a,{className:"StickerSetModal",isOpen:e,onClose:c,hasCloseButton:!0,title:a?a.title:"Sticker Set"},a&&a.stickers?n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{ref:i,className:"stickers custom-scroll"},a.stickers.map(e=>n.a.createElement(ia,{sticker:e,size:l.vb,observeIntersection:d,onClick:m,clickArg:e}))),n.a.createElement("div",{className:"button-wrapper"},n.a.createElement(B.a,{size:"smaller",fluid:!0,color:a.installedDate?"danger":"primary",onClick:u},`${a.installedDate?"Remove":"Add"} ${a.count} stickers`))):n.a.createElement(he.a,null))})),wn=a(113);a(273);var Pn=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);return!a||a.isRestricted?{}:{chat:a,isMuted:a.isMuted,isPrivate:Object(m.kb)(a.id),canDeleteChat:Object(m.d)(a)}},(e,t)=>Object(u.l)(t,["updateChatMutedState","enterMessageSelectMode"]))(({chatId:e,isOpen:t,anchor:a,isChannel:c,canSubscribe:r,canSearch:s,canMute:l,canSelect:i,canLeave:d,chat:m,isPrivate:u,isMuted:h,canDeleteChat:b,onSubscribeChannel:p,onSearchClick:g,onClose:v,onCloseAnimationEnd:E,updateChatMutedState:f,enterMessageSelectMode:O})=>{const[j,C]=Object(n.r)(!0),[y,k]=Object(n.r)(!1),{x:N,y:I}=a;Object(W.a)(t,E,void 0,!1);const S=Object(n.m)(()=>{C(!1),k(!0)},[]),w=Object(n.m)(()=>{C(!1),v()},[v]),P=Object(n.m)(()=>{k(!1),v()},[v]),M=Object(n.m)(()=>{f({chatId:e,isMuted:!h}),w()},[e,w,h,f]),L=Object(n.m)(()=>{p(),w()},[w,p]),A=Object(n.m)(()=>{g(),w()},[w,g]),T=Object(n.m)(()=>{O(),w()},[w,O]);Object(n.n)(()=>(En(),fn),[]);const B=Object(F.a)();return n.a.createElement(wn.a,null,n.a.createElement("div",{className:"HeaderMenuContainer"},n.a.createElement(kn.a,{isOpen:j,positionX:"right",style:`left: ${N}px;top: ${I}px;`,onClose:w},o.f&&r&&n.a.createElement(q.a,{icon:c?"channel":"group",onClick:L},B(c?"Subscribe":"Join Group")),o.f&&s&&n.a.createElement(q.a,{icon:"search",onClick:A},B("Search")),l&&n.a.createElement(q.a,{icon:h?"unmute":"mute",onClick:M},B(h?"ChatsUnmute":"ChatsMute")),i&&n.a.createElement(q.a,{icon:"select",onClick:T},B("ReportSelectMessages")),d&&n.a.createElement(q.a,{destructive:!0,icon:"delete",onClick:S},B(u?"Delete":b?"Delete and Leave":"Leave"))),m&&n.a.createElement(Ge.a,{isOpen:y,onClose:P,chat:m})))})),Mn=a(144);a(274);const Fn=Object(V.a)(e=>e(),200,!1);var Ln=Object(n.h)(Object(c.h)(e=>{const t=Object(d.r)(e);if(!t)return{};const{query:a,results:n}=Object(d.A)(e)||{},{totalCount:c,foundIds:r}=n||{};return{chat:t,query:a,totalCount:c,foundIds:r}},(e,t)=>Object(u.l)(t,["setLocalTextSearchQuery","searchTextMessagesLocal","focusMessage","closeLocalTextSearch","searchMessagesByDate"]))(({isActive:e,chat:t,query:a,totalCount:c,foundIds:r,setLocalTextSearchQuery:s,searchTextMessagesLocal:l,focusMessage:o,closeLocalTextSearch:i,searchMessagesByDate:d})=>{const m=Object(n.q)(null),[u,h]=Object(n.r)(0),[b,p,g]=Object(Ae.a)();Object(n.n)(()=>{const{visualViewport:e}=window;if(!e)return;const t=document.getElementById("Main"),a=()=>{const{activeElement:a}=document;if(a&&a===m.current){const{pageTop:a,height:n}=e;t.style.transform=`translateY(${a}px)`,t.style.height=n+"px",document.documentElement.scrollTop=a}else t.style.transform="",t.style.height=""};return e.addEventListener("resize",a),()=>{e.removeEventListener("resize",a)}},[]),Object(n.n)(()=>{t&&r&&r.length?(o({chatId:t.id,messageId:r[r.length-1]}),h(0)):h(-1)},[t,o,r]),Object(n.n)(()=>{Array.from(document.querySelectorAll("input")).forEach(t=>{t.disabled=Boolean(e&&t!==m.current)}),Array.from(document.querySelectorAll("div[contenteditable]")).forEach(t=>{t.contentEditable=e?"false":"true"})},[e]),Object(n.n)(()=>{e||m.current.blur()},[e]),Object(n.o)(()=>{document.querySelector("#MobileSearch input").blur()},[b]);const v=Object(n.m)(e=>{s({query:e}),e.length&&Fn(l)},[l,s]),E=Object(n.m)(e=>{d({timestamp:e.valueOf()/1e3}),g()},[g,d]),f=Object(n.m)(()=>{if(t&&r){const e=u+1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),O=Object(n.m)(()=>{if(t&&r){const e=u-1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),j=Object(F.a)();return n.a.createElement("div",{id:"MobileSearch",className:e?"active":""},n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{size:"smaller",round:!0,color:"translucent",onClick:i},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement(Mn.a,{ref:m,value:a,onChange:v})),n.a.createElement("div",{className:"footer"},n.a.createElement("div",{className:"counter"},a?r&&r.length?`${u+1} of ${c}`:r&&!r.length?"No results":"":n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:p,ariaLabel:"Search messages by date"},n.a.createElement("i",{className:"icon-calendar"}))),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:f,disabled:!r||!r.length||u===r.length-1},n.a.createElement("i",{className:"icon-up"})),n.a.createElement(B.a,{round:!0,size:"smaller",color:"translucent",onClick:O,disabled:!r||!r.length||0===u},n.a.createElement("i",{className:"icon-down"}))),n.a.createElement(Pe,{isOpen:b,isPastMode:!0,submitButtonLabel:j("JumpToDate"),onClose:g,onSubmit:E}))})),An=a(53),Tn=a(180),Bn=a(168),Dn=a(172);var xn=function(e,t){const a=e.scrollTop,n=a+e.offsetHeight,c=t.offsetTop,r=c+t.offsetHeight;return c>a&&r{const l=Object(n.q)(null),{shouldRender:o,transitionClassNames:i}=Object(W.a)(e,void 0,void 0,!1),d=Object(n.m)(e=>{if(!s)return-1;const t=s.length;return Object(Rn.a)(t,e)},[s]),[m,u]=Object(n.r)(-1),h=Object(n.m)((e,t)=>{t.preventDefault(),u(t=>d(t+e))},[u,d]),b=Object(n.m)((e,t=!1)=>{const a=r&&r[e];a&&c(a,t)},[r,c]),p=Object(n.m)(e=>{if(s&&s.length&&m>-1){const t=s[m];t&&(e.preventDefault(),b(t.userId,!0))}},[s,m,b]);Object(n.n)(()=>e?Object(Te.a)({onEsc:a,onUp:e=>h(-1,e),onDown:e=>h(1,e),onEnter:p,onTab:p}):void 0,[e,a,h,p]),Object(n.n)(()=>{s&&!s.length&&a()},[s,a]),Object(n.n)(()=>{u(0)},[t]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a||e<0)return;const{visibleIndexes:n,allElements:c}=function(e,t,a=0,n=!1,c=!1){const r=e.scrollTop,s=r+e.offsetHeight,l="string"==typeof t?e.querySelectorAll(t):t,{length:o}=l,i=[];let d=!1;for(let e=0;e=r-a&&m<=s+a:o<=s+a&&m>=r-a)i.push(e),d=!0;else if(d&&!n)break}return{allElements:l,visibleIndexes:i}}(a,".chat-item-clickable",8,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!xn(a,c[r])){const t=e>n[n.length-1]?"start":"end";Object(Un.a)(a,c[e],t,10)}}(m,l)},[m]);const g=Object(O.a)(s&&s.length?s:void 0,o),v=s&&!s.length?g:s;if(!o||v&&!v.length)return;const E=Object(ce.a)("MentionMenu custom-scroll",i);return n.a.createElement("div",{className:E,ref:l},v&&v.map(({userId:e},t)=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable scroll-item",onClick:()=>b(e),focus:m===t},n.a.createElement(Ee.a,{userId:e,avatarSize:"small",withUsername:!0}))))});a(276);var zn=Object(n.h)(({attachments:e,caption:t,canSuggestMembers:a,groupChatMembers:c,currentUserId:r,usersById:s,onCaptionUpdate:o,onSend:i,onClear:d})=>{const m=Object(O.a)(e),u=e.length?e:m,h=Boolean(e.length),{isMentionMenuOpen:p,mentionFilter:g,closeMentionMenu:v,insertMention:E,mentionFilteredMembers:f}=Object(Tn.a)(a&&h,t,o,l.v,c,r,s);Object(n.n)(()=>h?Object(b.a)(d):void 0,[h,d]);const j=Object(n.m)(()=>{h&&i()},[h,i]),C=Object(F.a)();if(!u)return;const y=u.every(e=>e.mimeType.startsWith("image/")),k=u.every(e=>e.mimeType.startsWith("video/"));let N="";N=y?1===u.length?"Send Photo":`Send ${u.length} Photos`:k?1===u.length?"Send Video":`Send ${u.length} Videos`:1===u.length?"Send File":`Send ${u.length} Files`;const I=u.every(e=>e.quick);return n.a.createElement(be.a,{isOpen:h,onClose:d,header:function(){if(u)return n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel attachments",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},N),n.a.createElement(B.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:j},C("Send")))}(),className:"AttachmentModal"},I?n.a.createElement("div",{className:"media-wrapper custom-scroll"},u.map(e=>e.mimeType.startsWith("image/")?n.a.createElement("img",{src:e.blobUrl,alt:""}):n.a.createElement("video",{src:e.blobUrl,autoPlay:!0,muted:!0,loop:!0}))):n.a.createElement("div",{className:"document-wrapper custom-scroll"},u.map(e=>n.a.createElement(Bn.a,{name:e.filename,extension:Object(An.d)(e.filename,e.mimeType),previewData:e.previewBlobUrl,size:e.size,smaller:!0}))),n.a.createElement("div",{className:"attachment-caption-wrapper"},n.a.createElement(Gn,{isOpen:p,onClose:v,filter:g,onInsertUserName:E,filteredChatMembers:f,usersById:s}),n.a.createElement(Dn.a,{id:"caption-input-text",html:t,editableInputId:l.v,placeholder:C("Caption"),onUpdate:o,onSend:i,shouldSetFocus:h})))}),qn=a(127);a(277);var $n=Object(n.h)(({isOpen:e,onSend:t,onClear:a})=>{const c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(null),[l,o]=Object(n.r)(""),[i,d]=Object(n.r)([""]),[m,u]=Object(n.r)(!0),[h,p]=Object(n.r)(!1),[g,v]=Object(n.r)(!1),[E,f]=Object(n.r)(),[O,j]=Object(n.r)(),[C,y]=Object(n.r)(!1),k=Object(n.m)(t=>{e&&t.current&&t.current.focus()},[e]);Object(n.n)(()=>e?Object(b.a)(a):void 0,[e,a]),Object(n.n)(()=>{e||(o(""),d([""]),u(!0),p(!1),v(!1),f(""),j(""),y(!1))},[e]),Object(n.n)(()=>k(c),[k,e]),Object(n.o)(()=>{const e=s.current;e&&E!==e.innerHTML&&(e.innerHTML=E)},[E]);const N=Object(n.m)((e=[])=>{d([...e,""]),requestAnimationFrame(()=>{const e=r.current;e&&(e.classList.toggle("overflown",e.scrollHeight>320),e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))})},[]),I=Object(n.m)(()=>{if(y(!1),!e)return;const a=l.trim().substring(0,255),n=i.map(e=>e.trim().substring(0,100)).filter(e=>e.length);if(!a||n.length<2)return o(a),n.length?n.length<2?N(n):d(n):N(),void y(!0);if(g&&(!O||!n[Number(O)]))return void y(!0);const c={summary:{question:a,answers:n.map((e,t)=>({text:e.trim(),option:String(t),...String(t)===O&&{correct:!0}})),...!m&&{isPublic:!0},...h&&{multipleChoice:!0},...g&&{quiz:!0}}};if(g){const{text:e,entities:t}=E&&Object(qn.a)(E.substring(0,200))||{};c.quiz={correctAnswers:[O],...e&&{solution:e},...t&&{solutionEntities:t}}}t(c)},[e,l,i,g,O,m,h,t,N,E]),S=Object(n.m)((e,t)=>{const a=[...i];a[e]=t,a[a.length-1].trim().length&&a.length<10?N(a):d(a)},[i,N]),w=Object(n.m)(e=>{const t=[...i];t.splice(e,1),d(t),requestAnimationFrame(()=>{r.current&&r.current.classList.toggle("overflown",r.current.scrollHeight>320)})},[i]),P=Object(n.m)(e=>{j(e)},[j]),M=Object(n.m)(e=>{u(e.target.checked)},[]),L=Object(n.m)(e=>{p(e.target.checked)},[]),A=Object(n.m)(e=>{v(e.target.checked)},[]),T=Object(n.m)(e=>{13===e.keyCode&&I()},[I]),D=Object(n.m)(()=>{if(C&&!l.trim().length)return"Please enter the question"},[C,l]),x=Object(n.m)(e=>{const t=i.map(e=>e.trim()).filter(e=>e.length);if(C&&t.length<2&&!i[e].trim().length)return"Please enter at least two options"},[C,i]),U=Object(F.a)();function R(){return i.map((e,t)=>n.a.createElement("div",{className:"option-wrapper"},n.a.createElement(pe.a,{label:t!==i.length-1||10===i.length?"Option "+(t+1):"Add an Option",error:x(t),value:e,onChange:e=>S(t,e.currentTarget.value),onKeyPress:T}),t!==i.length-1&&n.a.createElement(B.a,{className:"option-remove-button",round:!0,color:"translucent",size:"smaller",ariaLabel:"Remove option",onClick:()=>w(t)},n.a.createElement("i",{className:"icon-close"}))))}return n.a.createElement(be.a,{isOpen:e,onClose:a,header:n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(B.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel poll creation",onClick:a},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},U("NewPoll")),n.a.createElement(B.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:I},U("Create"))),className:"PollModal"},n.a.createElement(pe.a,{ref:c,label:U("AskAQuestion"),value:l,error:D(),onChange:e=>o(e.currentTarget.value),onKeyPress:T}),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"options-list custom-scroll",ref:r},n.a.createElement("h3",{className:"options-header"},"Options"),C&&function(){const e=i.map(e=>e.trim()).filter(e=>e.length);return g&&(!O||!e[Number(O)])&&n.a.createElement("p",{className:"error"},"Please choose the correct answer")}(),g?n.a.createElement(ca.a,{name:"correctOption",options:R().map((e,t)=>({value:String(t),label:e,hidden:t===i.length-1})),onChange:P}):R()),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"quiz-mode"},n.a.createElement(_t.a,{label:U("PollAnonymous"),checked:m,onChange:M}),n.a.createElement(_t.a,{label:U("PollMultiple"),checked:h,disabled:g,onChange:L}),n.a.createElement(_t.a,{label:U("PollQuiz"),checked:g,disabled:h,onChange:A}),g&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"options-header"},"Solution"),n.a.createElement("div",{ref:s,className:"form-control",contentEditable:!0,onChange:e=>f(e.currentTarget.innerHTML)}),n.a.createElement("div",{className:"note"},"Users will see this comment after choosing a wrong answer, good for educational purposes."))))});let Hn;function Vn(e,t,a=250){const c=Object(n.q)(!1);Object(n.n)(()=>{Hn&&(clearTimeout(Hn),Hn=void 0),e&&!o.k&&(Hn=window.setTimeout(()=>{c.current||t()},2*a))},[e,a,t]);return[Object(n.m)(()=>{c.current=!0},[]),Object(n.m)(()=>{c.current=!1,Hn&&(clearTimeout(Hn),Hn=void 0),Hn=window.setTimeout(()=>{c.current||t()},a)},[a,t])]}var Yn=a(67),Wn=a(145);a(278);var Kn=Object(n.h)(({emoji:e,onClick:t})=>{const a=Object(n.m)(()=>{t(e.native,e.id)},[e,t]);return n.a.createElement("div",{className:"EmojiButton",onClick:a,title:e.colons},o.c?e.native:n.a.createElement("img",{src:`/img-apple-64/${e.image}.png`,alt:"",loading:"lazy"}))});var Qn=Object(n.h)(({category:e,index:t,allEmojis:a,observeIntersection:c,shouldRender:r,onEmojiSelect:s})=>{const l=Object(n.q)(null);Object(aa.c)(l,c);const{transitionClassNames:i}=Object(W.a)(r,void 0,void 0,"slow"),d=Object(F.a)(),m=o.f?Math.floor((y.a.get().width-8)/44):9,u=44*Math.ceil(e.emojis.length/m);return n.a.createElement("div",{ref:l,key:e.id,id:"emoji-category-"+t,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},d("recent"===e.id?"RecentStickers":"Emoji"+t)),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",i),style:`height: ${u}px;`},r&&e.emojis.map(e=>{const t=a[e],c="id"in t?t:t[1];return n.a.createElement(Kn,{key:c.id,emoji:c,onClick:s})})))});a(279);const Zn={recent:"icon-recent",people:"icon-smile",nature:"icon-animals",foods:"icon-eats",activity:"icon-sport",places:"icon-car",objects:"icon-lamp",symbols:"icon-language",flags:"icon-flag"},Xn=[];let _n,Jn,ec;var tc=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["recentEmojis"]),(e,t)=>Object(u.l)(t,["addRecentEmoji"]))(({className:e,onEmojiSelect:t,recentEmojis:c,addRecentEmoji:r})=>{const s=Object(n.q)(null),i=Object(n.q)(null),[d,m]=Object(n.r)(),[u,h]=Object(n.r)(),[b,p]=Object(n.r)(0),{observe:g}=Object(aa.a)({rootRef:s,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("emoji-category-"))return;const a=Number(t.replace("emoji-category-",""));Xn[a]=e.isIntersecting});const t=Xn.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&p(t[Math.floor(t.length/2)].index)});Object(qe.a)(i,!o.f),Object(n.n)(()=>{if(!d)return;const e=i.current;if(!e)return;const t=42*b-e.offsetWidth/2+21;Object(Wn.a)(e,t)},[d,b]);const v=Object(F.a)(),E=Object(n.p)(()=>{if(!d)return Ue.a;const e=[...d];return c&&c.length&&e.unshift({id:"recent",name:v("RecentStickers"),emojis:c}),e},[d,v,c]);Object(n.n)(()=>{setTimeout(()=>{const e=()=>{m(ec.categories),h(ec.emojis)};ec?e():async function(){_n||(_n=a.e(8).then(a.t.bind(null,306,3)),Jn=(await _n).default,ec=Object(Yn.b)(Jn));return _n}().then(e)},200)},[]);const f=Object(n.m)(e=>{p(e);const t=document.getElementById("emoji-category-"+e);Object(Un.a)(s.current,t,"start",50,800)},[]),O=Object(n.m)((e,a)=>{t(e),r({emoji:a})},[r,t]),j=Object(ct.a)([],l.S);const C=Object(ce.a)("EmojiPicker",e);return u&&j?n.a.createElement("div",{className:C},n.a.createElement("div",{ref:i,className:"EmojiPicker-header"},E.map((function(e,t){const a=Zn[e.id];return a&&n.a.createElement(B.a,{className:"symbol-set-button "+(t===b?"activated":""),round:!0,faded:!0,color:"translucent",onClick:()=>f(t),ariaLabel:e.name},n.a.createElement("i",{className:a}))}))),n.a.createElement("div",{ref:s,className:"EmojiPicker-main no-selection no-scrollbar"},E.map((e,t)=>n.a.createElement(Qn,{category:e,index:t,allEmojis:u,observeIntersection:g,shouldRender:b>=t-1&&b<=t+1,onEmojiSelect:O})))):n.a.createElement("div",{className:C},n.a.createElement(he.a,null))}));const ac=o.f?8:16;var nc=Object(n.h)(({stickerSet:e,loadAndPlay:t,index:a,observeIntersection:c,shouldRender:r,onStickerSelect:s,onStickerUnfave:i})=>{const d=Object(n.q)(null);Object(aa.c)(d,c);const{transitionClassNames:m}=Object(W.a)(r,void 0,void 0,"slow"),u=o.f?Math.floor((y.a.get().width-8)/(l.wb+ac)):5,h=Math.ceil(e.count/u)*(l.wb+ac);return n.a.createElement("div",{ref:d,key:e.id,id:"sticker-set-"+a,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},e.title),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",m),style:`height: ${h}px;`},r&&e.stickers&&e.stickers.map(a=>n.a.createElement(ia,{key:a.id,sticker:a,size:l.wb,observeIntersection:c,noAnimate:!t,onClick:s,clickArg:a,onUnfaveClick:"favorite"===e.id?i:void 0}))))});a(280);const cc=[];var rc=Object(n.h)(Object(c.h)(e=>{const{setsById:t,added:a,recent:n,favorite:c}=e.stickers;return{recentStickers:n.stickers,favoriteStickers:c.stickers,stickerSetsById:t,addedSetIds:a.setIds,shouldPlay:e.settings.byKey.shouldLoopStickers}},(e,t)=>Object(u.l)(t,["loadStickerSets","loadRecentStickers","loadFavoriteStickers","loadAddedStickers","addRecentSticker","unfaveSticker"]))(({className:e,loadAndPlay:t,canSendStickers:a,recentStickers:c,favoriteStickers:r,addedSetIds:s,stickerSetsById:o,shouldPlay:i,onStickerSelect:d,loadStickerSets:m,loadRecentStickers:u,loadFavoriteStickers:h,loadAddedStickers:b,addRecentSticker:p,unfaveSticker:g})=>{const v=Object(n.q)(null),E=Object(n.q)(null),[f,O]=Object(n.r)(0),{observe:j}=Object(aa.a)({rootRef:v,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("sticker-set-"))return;const a=Number(t.replace("sticker-set-",""));cc[a]=e.isIntersecting});const t=cc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&O(t[Math.floor(t.length/2)].index)}),{observe:C}=Object(aa.a)({rootRef:E}),y=Object(F.a)(),k=Boolean(s),N=Object(n.p)(()=>s?[{id:"recent",title:y("RecentStickers"),stickers:c,count:c.length},{id:"favorite",title:y("FavoriteStickers"),stickers:r,count:r.length},...s.map(e=>o[e]).filter(Boolean)]:Ue.a,[s,y,c,r,o]),I=Object(n.p)(()=>k&&0===N.filter(e=>e.stickers&&e.stickers.length).length,[N,k]);Object(n.n)(()=>{t&&(m(),u(),h())},[t,h,u,m]),Object(n.n)(()=>{s&&s.length&&b()},[s,b]),Object(qe.a)(E),Object(n.n)(()=>{if(!k)return;const e=E.current;if(!e)return;const t=52*f-(e.offsetWidth/2-26);Object(Wn.a)(e,t)},[k,f]);const S=Object(n.m)(e=>{O(e);const t=document.getElementById("sticker-set-"+e);Object(Un.a)(v.current,t,"start",void 0,500)},[]),w=Object(n.m)(e=>{d(e),p({sticker:e})},[p,d]),P=Object(n.m)(e=>{g({sticker:e})},[g]),M=Object(ct.a)([],l.nb);const L=Object(ce.a)("StickerPicker",e);return k&&M&&!I&&a?n.a.createElement("div",{className:L},n.a.createElement("div",{ref:E,className:"StickerPicker-header no-selection no-scrollbar"},N.map((function(e,t){const a=e.stickers&&e.stickers[0],c=Object(ce.a)("symbol-set-button sticker-set-button",t===f&&"activated");return"recent"===e.id||"favorite"===e.id||e.hasThumbnail||!a?n.a.createElement(B.a,{key:e.id,className:c,ariaLabel:e.title,round:!0,faded:"recent"===e.id||"favorite"===e.id,color:"translucent",onClick:()=>S(t)},"recent"===e.id?n.a.createElement("i",{className:"icon-recent"}):"favorite"===e.id?n.a.createElement("i",{className:"icon-favorite"}):e.isAnimated?n.a.createElement(la,{stickerSet:e,observeIntersection:C}):n.a.createElement(oa,{stickerSet:e,observeIntersection:C})):n.a.createElement(ia,{key:e.id,sticker:a,size:l.xb,title:e.title,className:c,observeIntersection:C,onClick:S,clickArg:t})}))),n.a.createElement("div",{ref:v,className:"StickerPicker-main no-scrollbar"},N.map((e,a)=>n.a.createElement(nc,{key:e.id,stickerSet:e,loadAndPlay:Boolean(i&&t),index:a,observeIntersection:j,shouldRender:f>=a-1&&f<=a+1,onStickerSelect:w,onStickerUnfave:P})))):n.a.createElement("div",{className:L},a?I?n.a.createElement("div",{className:"picker-disabled"},"You have no saved Stickers."):n.a.createElement(he.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending stickers is not allowed in this chat."))}));a(281);function sc(){return(sc=Object.assign||function(e){for(var t=1;t{const s=Object(n.q)(null),l=Object(n.q)(null),o="gif"+e.id,i=Object(aa.b)(s,t)&&!a,d=Object(v.a)(o+"?size=m",!i,r.ApiMediaFormat.BlobUrl),m=Object(ka.a)(e.thumbnail&&e.thumbnail.dataUri,Boolean(d)),u=d||m,h=Object(v.a)(o,!i,r.ApiMediaFormat.BlobUrl),b=Boolean(i&&h),{transitionClassNames:p}=Object(ra.a)(u||h,"slow"),{isBuffered:g,bufferingHandlers:E}=Object(K.a)(!0),f=i&&!g;Object(Z.a)(l,[b]);const O=Object(n.m)(()=>c({...e,blobUrl:h}),[c,e,h]),j=Object(ce.a)("GifButton",e.width&&e.height&&e.width({savedGifs:e.gifs.saved.gifs}),(e,t)=>Object(u.l)(t,["loadSavedGifs"]))(({className:e,loadAndPlay:t,canSendGifs:a,savedGifs:c,onGifSelect:r,loadSavedGifs:s})=>{const o=Object(n.q)(null),{observe:i}=Object(aa.a)({rootRef:o,debounceMs:300});Object(n.n)(()=>{t&&s()},[t,s]);const d=Object(ct.a)([],l.nb);return n.a.createElement("div",{ref:o,className:Object(ce.a)("GifPicker no-scrollbar",e)},a?d&&c&&c.length?c.map(e=>n.a.createElement(lc,{key:e.id,gif:e,observeIntersection:i,isDisabled:!t,onClick:r})):d&&c?n.a.createElement("div",{className:"picker-disabled"},"No saved GIFs."):n.a.createElement(he.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending GIFs is not allowed in this chat."))}));let ic;!function(e){e[e.Emoji=0]="Emoji",e[e.Stickers=1]="Stickers",e[e.GIFs=2]="GIFs"}(ic||(ic={}));const dc=Object.values(ic).filter(e=>"string"==typeof e),mc={[ic.Emoji]:"icon-smile",[ic.Stickers]:"icon-stickers",[ic.GIFs]:"icon-gifs"};var uc=Object(n.h)(({activeTab:e,onSwitchTab:t,onRemoveSymbol:a,onSearchOpen:c})=>{function r(a){return n.a.createElement(B.a,{className:"symbol-tab-button "+(e===a?"activated":""),onClick:()=>t(a),ariaLabel:dc[a],round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:mc[a]}))}const s=Object(n.m)(()=>{c(e===ic.Stickers?"stickers":"gifs")},[e,c]);return n.a.createElement("div",{className:"SymbolMenu-footer",onClick:function(e){e.stopPropagation()}},e!==ic.Emoji&&n.a.createElement(B.a,{className:"symbol-search-button",ariaLabel:e===ic.Stickers?"Search Stickers":"Search GIFs",round:!0,faded:!0,color:"translucent",onClick:s},n.a.createElement("i",{className:"icon-search"})),r(ic.Emoji),r(ic.Stickers),r(ic.GIFs),e===ic.Emoji&&n.a.createElement(B.a,{className:"symbol-delete-button",onClick:a,ariaLabel:"Remove Symbol",round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:"icon-delete-left"})))});a(283);let hc=!1;var bc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onLoad:a,onClose:c,onEmojiSelect:r,onStickerSelect:s,onGifSelect:l,onRemoveSymbol:i,onSearchOpen:d})=>{const[m,u]=Object(n.r)(0),[h,b]=Vn(e,c),{shouldRender:p,transitionClassNames:g}=Object(W.a)(e,c,!1,!1);!hc&&e&&(hc=!0),Object(n.n)(()=>{a()},[a]),Object(n.o)(()=>{if(o.f)return e&&(document.body.classList.add("enable-symbol-menu-transforms"),document.body.classList.add("is-symbol-menu-open")),()=>{e&&Object(V.b)(()=>{document.body.classList.remove("is-symbol-menu-open"),setTimeout(()=>{document.body.classList.remove("enable-symbol-menu-transforms")},350)})}},[e]);const v=Object(n.m)(e=>{c(),d(e)},[c,d]),E=Object(F.a)(),{canSendStickers:f,canSendGifs:O}=t;function j(t,a){switch(m){case ic.Emoji:return n.a.createElement(tc,{className:"picker-tab",onEmojiSelect:r});case ic.Stickers:return n.a.createElement(rc,{className:"picker-tab",loadAndPlay:!!f&&(e&&(t||a)),canSendStickers:f,onStickerSelect:s});case ic.GIFs:return n.a.createElement(oc,{className:"picker-tab",loadAndPlay:!!O&&(e&&(t||a)),canSendGifs:O,onGifSelect:l})}}const C=n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"SymbolMenu-main",onClick:function(e){e.stopPropagation()}},hc&&n.a.createElement(T.a,{name:"slide",activeKey:m,renderCount:dc.length},j)),o.f&&n.a.createElement(B.a,{round:!0,faded:!0,color:"translucent",ariaLabel:E("Close"),className:"symbol-close-button",size:"tiny",onClick:c},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(uc,{activeTab:m,onSwitchTab:u,onRemoveSymbol:i,onSearchOpen:v}));if(o.f){if(!p)return;const e=Object(ce.a)("SymbolMenu mobile-menu",g);return n.a.createElement(wn.a,null,n.a.createElement("div",{className:e},C))}return n.a.createElement(kn.a,{isOpen:e,positionX:"left",positionY:"bottom",onClose:c,className:"SymbolMenu",onCloseAnimationEnd:c,onMouseEnter:o.k?void 0:h,onMouseLeave:o.k?void 0:b,noCloseOnBackdrop:!o.k},C)});a(284);var pc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onFileSelect:a,onPollCreate:c,onClose:r})=>{const[s,i]=Vn(e,r),d=Object(n.m)((e,t)=>{const{files:n}=e.target;n&&n.length>0&&a(Array.from(n),t)},[a]),m=Object(n.m)(()=>{ga(l.k,e=>d(e,!0))},[d]),u=Object(n.m)(()=>{ga("*",e=>d(e,!1))},[d]),h=Object(F.a)(),{canAttachMedia:b,canAttachPolls:p}=t;return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:r,className:"AttachMenu fluid",onCloseAnimationEnd:r,onMouseEnter:o.k?void 0:s,onMouseLeave:o.k?void 0:i,noCloseOnBackdrop:!o.k},!b&&n.a.createElement(q.a,{className:"media-disabled",disabled:!0},"Posting media content is not allowed in this group."),b&&n.a.createElement(n.a.Fragment,null,n.a.createElement(q.a,{icon:"photo",onClick:m},h("AttachmentMenu.PhotoOrVideo")),n.a.createElement(q.a,{icon:"document",onClick:u},"Document")),p&&n.a.createElement(q.a,{icon:"poll",onClick:c},h("Poll")))});a(285);var gc=Object(n.h)(Object(c.h)(e=>{const{stickers:t}=e.stickers.forEmoji;return{stickers:t}},(e,t)=>Object(u.l)(t,["clearStickersForEmoji"]))(({isOpen:e,onStickerSelect:t,stickers:a,clearStickersForEmoji:c})=>{const r=Object(n.q)(null),{shouldRender:s,transitionClassNames:i}=Object(W.a)(e,void 0,void 0,!1),d=Object(O.a)(a,!0),m=a||d,{observe:u}=Object(aa.a)({rootRef:r,throttleMs:200});Object(n.n)(()=>e?Object(b.a)(c):void 0,[e,c]);const h=Object(ce.a)("EmojiTooltip custom-scroll",i);return n.a.createElement("div",{ref:r,className:h,onMouseEnter:o.k?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.k?void 0:()=>{document.body.classList.remove("no-select")}},s&&m?m.map(e=>n.a.createElement(ia,{key:e.id,sticker:e,size:l.wb,observeIntersection:u,onClick:t,clickArg:e})):s?n.a.createElement(he.a,null):void 0)}));a(286);var vc=Object(n.h)(Object(c.h)((e,{messageId:t})=>{const{chatId:a}=Object(d.y)(e)||{};return a?{message:Object(d.k)(e,a,t)}:{}},(e,t)=>Object(u.l)(t,["clickInlineButton"]))(({isOpen:e,message:t,onClose:a,clickInlineButton:c})=>{const[r,s]=Vn(e,a);if(t&&t.keyboardButtons)return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:a,className:"KeyboardMenu",onCloseAnimationEnd:a,onMouseEnter:o.k?void 0:r,onMouseLeave:o.k?void 0:s,noCloseOnBackdrop:!o.k},n.a.createElement("div",{className:"content"},t.keyboardButtons.map(e=>n.a.createElement("div",{className:"row"},e.map(e=>n.a.createElement(B.a,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>c({button:e})},e.text))))))}));a(287);var Ec=Object(n.h)(({isOpen:e,onSilentSend:t,onScheduleSend:a,onClose:c,onCloseAnimationEnd:r})=>{const[s,l]=Vn(e,c),i=Object(F.a)();return n.a.createElement(kn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",className:"CustomSendMenu",onClose:c,onCloseAnimationEnd:r,onMouseEnter:o.k?void 0:s,onMouseLeave:o.k?void 0:l,noCloseOnBackdrop:!o.k},t&&n.a.createElement(q.a,{icon:"mute",onClick:t},i("SendWithoutSound")),a&&n.a.createElement(q.a,{icon:"schedule",onClick:a},i("ScheduleMessage")))}),fc=a(128),Oc=a(154),jc=a(161);a(288);var Cc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(d.m)(e,a.id);if(!a||!n)return{};const{query:c,results:r}=Object(d.A)(e)||{},{totalCount:s,foundIds:l}=r||{};return{chat:a,messagesById:n,query:c,totalCount:s,foundIds:l}},(e,t)=>Object(u.l)(t,["searchTextMessagesLocal","focusMessage"]))(({chatId:e,threadId:t,chat:a,messagesById:r,query:s,totalCount:l,foundIds:o,searchTextMessagesLocal:i,focusMessage:h})=>{const b=Object(n.p)(()=>{if(!(s&&o&&o.length&&r))return Ue.a;const n=o.map(n=>{const s=r[n];if(!s)return;const l=s.senderId?Object(d.Db)(Object(c.e)(),s.senderId):void 0;let o;if(a&&Object(m.ib)(a))o=a;else if(s.forwardInfo){const{isChannelPost:e,fromChatId:t}=s.forwardInfo;o=e&&t?Object(d.f)(Object(c.e)(),t):void 0}else o=s.senderId?Object(d.f)(Object(c.e)(),s.senderId):void 0;return{message:s,senderUser:l,senderChat:o,onClick:()=>h({chatId:e,threadId:t,messageId:n})}}).filter(Boolean);return Object(u.k)(n,({message:e})=>e.date,"desc")},[e,t,h,o,a,r,s]);return n.a.createElement(ge.a,{className:"RightSearch custom-scroll",items:b,preloadBackwards:0,onLoadMore:i,noFastList:!0},n.a.createElement("p",{className:"helper-text"},s?1===l?"1 message found":(b.length&&(l||b.length)||"No")+" messages found":"Search messages"),b.map(({message:e,senderUser:t,senderChat:a,onClick:c})=>{const r=a?Object(m.l)(a):Object(m.Y)(t),l=Object(m.M)(e);return n.a.createElement(ve.a,{className:"chat-item-clickable search-result-message m-0",onClick:c},n.a.createElement(U.a,{chat:a,user:t}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",null,r&&Object(x.a)(r)),n.a.createElement(jc.a,{message:e})),n.a.createElement("div",{className:"subtitle"},Object(x.a)(l,["emoji","highlight"],{highlight:s}))))}))})),yc=a(103);var kc=Object(n.h)(Object(c.h)((e,{stickerSetId:t})=>({set:Object(d.ub)(e,t),shouldPlay:Object(d.tb)(e)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet"]))(({stickerSetId:e,observeIntersection:t,set:a,shouldPlay:c,loadStickers:r,toggleStickerSet:s,isSomeModalOpen:o,onModalToggle:i})=>{const d=a&&Boolean(a.installedDate),m=Boolean(a&&a.stickers),[u,h,b]=Object(Ae.a)();Object(yc.a)(()=>{i(u)},[u,i]);const p=Object(n.p)(()=>{if(!a)return[];const e=(a.covers||[]).map(({id:e})=>e),t=a.stickers?a.stickers.filter(({id:t})=>!e.includes(t)):[];return[...a.covers||[],...t].slice(0,5)},[a]);Object(n.n)(()=>{!m&&p.length<5&&r({stickerSetId:e})},[m,p.length,r,e]);const g=Object(n.m)(()=>{s({stickerSetId:e})},[s,e]);if(!a)return;const v=p.length>0;return n.a.createElement("div",{key:a.id,className:"sticker-set"},n.a.createElement("div",{className:"sticker-set-header"},n.a.createElement("div",{className:"title-wrapper"},n.a.createElement("h3",{className:"title"},a.title),n.a.createElement("p",{className:"count"},a.count," stickers")),n.a.createElement(B.a,{className:d?"is-added":void 0,color:"primary",size:"tiny",pill:!0,fluid:!0,onClick:g},d?"Added":"Add")),n.a.createElement("div",{className:"sticker-set-main"},!v&&n.a.createElement(L.a,null),v&&p.map(e=>n.a.createElement(ia,{sticker:e,size:l.yb,observeIntersection:t,noAnimate:!c||u||o,onClick:h}))),v&&n.a.createElement(ma.a,{isOpen:u,fromSticker:p[0],onClose:b}))}));a(289);const Nc=Object(V.g)(e=>e(),6e4,!0);var Ic=Object(n.h)(Object(c.h)(e=>{const t=Object(d.z)(e),{query:a,resultIds:n}=t||{},{featured:c}=e.stickers;return{query:a,featuredIds:c.setIds,resultIds:n}},(e,t)=>Object(u.l)(t,["loadFeaturedStickers"]))(({query:e,featuredIds:t,resultIds:a,loadFeaturedStickers:c})=>{const r=Object(n.q)(null),[s,l]=Object(n.r)(!1),{observe:o}=Object(aa.a)({rootRef:r,throttleMs:200});return Object(n.n)(()=>{Nc(()=>{c()})}),n.a.createElement("div",{ref:r,className:"StickerSearch custom-scroll"},function(){if(void 0!==e)return!e&&t?t.map(e=>n.a.createElement(kc,{key:e,stickerSetId:e,observeIntersection:o,isSomeModalOpen:s,onModalToggle:l})):a?a.length?a.map(e=>n.a.createElement(kc,{key:e,stickerSetId:e,observeIntersection:o,isSomeModalOpen:s,onModalToggle:l})):n.a.createElement("p",{className:"helper-text"},"Nothing found."):n.a.createElement(he.a,null)}())}));a(290);var Sc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.s)(e),{query:a,results:n}=t||{},{chatId:c}=Object(d.y)(e)||{},r=c?Object(d.f)(e,c):void 0;return{query:a,results:n,chat:r,isChatWithBot:r?Object(d.N)(e,r):void 0}},(e,t)=>Object(u.l)(t,["searchMoreGifs","sendMessage","setGifSearchQuery"]))(({query:e,results:t,chat:a,isChatWithBot:c,searchMoreGifs:r,sendMessage:s,setGifSearchQuery:l})=>{const i=Object(n.q)(null),{observe:d}=Object(aa.a)({rootRef:i,debounceMs:300}),{canSendGifs:u}=Object(m.c)(a,c),h=Object(n.m)(e=>{u&&s({gif:e}),o.k&&l({query:void 0})},[u,s,l]),b=Object(F.a)();const p=Boolean(void 0!==e&&t&&t.length);return n.a.createElement("div",{className:"GifSearch"},n.a.createElement(ge.a,{ref:i,className:Object(ce.a)("gif-container custom-scroll",p&&"grid"),items:t,itemSelector:".GifButton",preloadBackwards:96,noFastList:!0,onLoadMore:r},function(){if(void 0!==e)return t?t.length?t.map(e=>n.a.createElement(lc,{key:e.id,gif:e,observeIntersection:d,onClick:h})):n.a.createElement("p",{className:"helper-text"},b("NoGIFsFound")):n.a.createElement(he.a,null)}()))}));a(291);var wc=Object(n.h)(Object(c.h)((e,{answer:t})=>{const{voters:a,offsets:n}=e.pollResults;return{voters:a&&a[t.option],offset:n&&n[t.option]||""}},(e,t)=>Object(u.l)(t,["loadPollOptionResults","openChat","closePollResults"]))(({chat:e,message:t,answer:a,answerVote:c,totalVoters:r,voters:s,offset:l,loadPollOptionResults:o,openChat:i,closePollResults:d})=>{const m=Object(O.a)(c.votersCount),[u,h]=Object(n.r)(!0),b=Boolean(s),{option:p,text:g}=a;Object(n.n)(()=>{b&&m===c.votersCount||o({chat:e,messageId:t.id,option:p,offset:l,limit:4,shouldResetVoters:!0})},[c.votersCount,b]);const v=Object(n.m)(()=>{h(!0),o({chat:e,messageId:t.id,option:p,offset:l,limit:50})},[e,o,t.id,l,p]);Object(n.n)(()=>{h(!1)},[s]);const E=Object(n.m)(e=>{i({id:e}),d()},[d,i]);return n.a.createElement("div",{className:"PollAnswerResults"},n.a.createElement("div",{className:"poll-voters"},s?s.map(e=>n.a.createElement(ve.a,{key:e,className:"chat-item-clickable",onClick:()=>E(e)},n.a.createElement(Ee.a,{avatarSize:"tiny",userId:e,forceShowSelf:!0,noStatusOrTyping:!0}))):n.a.createElement(he.a,null),s&&function(){const e=c.votersCount-s.length;return c.votersCount>4&&e>0&&n.a.createElement(Kt,{count:e,itemName:"voter",isLoading:u,onClick:v})}()),n.a.createElement("div",{className:"answer-head"},n.a.createElement("span",{className:"answer-title"},g),n.a.createElement("span",{className:"answer-percent"},(f=c.votersCount,(j=r)>0?(f/j*100).toFixed():0),"%")));var f,j}));a(292);var Pc=Object(n.h)(Object(c.h)(e=>{const{pollResults:{chatId:t,messageId:a},lastSyncTime:n}=e;if(!t||!a)return{};return{chat:Object(d.f)(e,t),message:Object(d.k)(e,t,a),lastSyncTime:n}})(({chat:e,message:t,lastSyncTime:a})=>{if(!t||!e)return n.a.createElement(he.a,null);const{summary:c,results:r}=Object(m.H)(t);if(!r.results)return;const s=Object(u.c)(r.results,"option");return n.a.createElement("div",{className:"PollResults"},n.a.createElement("h3",{className:"poll-question"},c.question),n.a.createElement("div",{className:"poll-results-list custom-scroll"},a&&c.answers.map(a=>n.a.createElement(wc,{key:`${t.id}-${a.option}`,chat:e,message:t,answer:a,answerVote:s[a.option],totalVoters:r.totalVoters})),!a&&n.a.createElement(he.a,null)))}));a(156);var Mc=Object(n.h)(Object(c.h)((e,{userId:t})=>{const a=Object(d.Db)(e,t),n=Object(d.f)(e,t),{progress:c}=e.management;return{user:a,chat:n,progress:c}},(e,t)=>Object(u.l)(t,["updateContact","deleteUser","closeManagement","openChat","deleteHistory"]))(({userId:e,user:t,chat:a,progress:c,updateContact:r,deleteUser:l,deleteHistory:o,closeManagement:i,openChat:d})=>{const[m,u,h]=Object(Ae.a)(),[b,p]=Object(n.r)(!1),[g,v]=Object(n.r)(),E=Object(F.a)(),f=t&&t.firstName||"",O=t&&t.lastName||"",j=a?a.isMuted:void 0,[C,y]=Object(n.r)(f),[k,N]=Object(n.r)(O),[I,S]=Object(n.r)(!j);Object(n.n)(()=>{S(!j)},[j]),Object(n.n)(()=>{p(!1),h()},[h,e]),Object(n.n)(()=>{y(f),N(O)},[f,O,t]),Object(n.n)(()=>{c===s.f.Complete&&(p(!1),v(void 0),h())},[h,c]);const w=Object(n.m)(e=>{y(e.target.value),p(!0)},[]),P=Object(n.m)(e=>{N(e.target.value),p(!0)},[]),M=Object(n.m)(e=>{S(e.target.checked),p(!0)},[]),A=Object(n.m)(()=>{const t=C.trim(),a=k.trim();t.length||v("Please provide first name"),r({userId:e,isMuted:!I,firstName:t,lastName:a})},[C,k,r,e,I]),T=Object(n.m)(()=>{a.lastMessage&&o({chatId:a.id,maxId:a.lastMessage.id,shouldDeleteForAll:!1}),l({userId:e}),h(),i(),d({id:void 0})},[a.id,a.lastMessage,h,i,o,l,d,e]);if(!t)return;const B=c===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{userId:t.id,avatarSize:"jumbo",status:"original name",withFullInfo:!0}),n.a.createElement(pe.a,{id:"user-first-name",label:E("UserInfo.FirstNamePlaceholder"),onChange:w,value:C,error:"Please provide first name"===g?g:void 0}),n.a.createElement(pe.a,{id:"user-last-name",label:E("UserInfo.LastNamePlaceholder"),onChange:P,value:k}),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(_t.a,{checked:I,label:E("Notifications"),subLabel:E(I?"UserInfo.NotificationsEnabled":"UserInfo.NotificationsDisabled"),onChange:M}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:u},E("DeleteContact")))),n.a.createElement(xt,{isShown:b,onClick:A,disabled:B,ariaLabel:E("Save")},B?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:m,onClose:h,text:E("AreYouSureDeleteContact"),confirmLabel:E("DeleteContact"),confirmHandler:T,confirmIsDestructive:!0}))}));var Fc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management,c=Boolean(a.fullInfo&&a.fullInfo.linkedChatId);return{chat:a,progress:n,isBasicGroup:Object(m.hb)(a),hasLinkedChannel:c,canChangeInfo:Object(m.q)(a,"changeInfo"),canBanUsers:Object(m.q)(a,"banUsers")}},(e,t)=>Object(u.l)(t,["togglePreHistoryHidden","updateChat","closeManagement","deleteHistory","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isBasicGroup:c,hasLinkedChannel:l,canChangeInfo:o,canBanUsers:i,onScreenSelect:d,togglePreHistoryHidden:u,updateChat:h,deleteHistory:b,leaveChannel:p,deleteChannel:g,closeManagement:E,openChat:f})=>{const[O,j,C]=Object(Ae.a)(),y=t.title,k=t.fullInfo&&t.fullInfo.about||"",[N,I]=Object(n.r)(!1),[S,w]=Object(n.r)(y),[P,M]=Object(n.r)(k),[A,T]=Object(n.r)(),[B,D]=Object(n.r)(),U=Object(m.f)(t),R=Object(v.a)(U,!1,r.ApiMediaFormat.BlobUrl),G=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(I(!1),D(void 0))},[a]);const z=Object(n.m)(()=>{d(s.g.ChatPrivacyType)},[d]),q=Object(n.m)(()=>{d(s.g.Discussion)},[d]),$=Object(n.m)(()=>{d(s.g.GroupPermissions)},[d]),H=Object(n.m)(()=>{d(s.g.ChatAdministrators)},[d]),V=Object(n.m)(e=>{T(e),I(!0)},[]),Y=Object(n.m)(e=>{w(e.target.value),I(!0)},[]),W=Object(n.m)(e=>{M(e.target.value),I(!0)},[]),K=Object(n.m)(()=>{const t=S.trim(),a=P.trim();t.length?h({chatId:e,title:t,about:a,photo:A}):D("Group title can't be empty")},[P,e,A,S,h]),Q=Object(n.m)(()=>{d(s.g.GroupMembers)},[d]),Z=Object(n.m)(()=>{if(!t.fullInfo)return;const{isPreHistoryHidden:e}=t.fullInfo;u({chatId:t.id,isEnabled:!e})},[t,u]),X=Object(n.p)(()=>{if(!t.defaultBannedRights)return 0;let e=["sendMessages","sendMedia","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages"].filter(e=>!t.defaultBannedRights[e]).length;const{sendStickers:a,sendGifs:n}=t.defaultBannedRights;return a||n||(e+=1),e},[t]),_=t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,J=Object(n.m)(()=>{c?b({chatId:t.id,maxId:t.lastMessage.id,shouldDeleteForAll:!1}):t.isCreator?g({chatId:t.id}):p({chatId:t.id}),C(),E(),f({id:void 0})},[c,t.isCreator,t.id,t.lastMessage,C,E,b,p,g,f]);if(t.isRestricted)return;const ee=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:R,onChange:V,disabled:!o}),n.a.createElement(pe.a,{id:"group-title",label:G("GroupName"),onChange:Y,value:S,error:"Group title can't be empty"===B?B:void 0,disabled:!o}),n.a.createElement(pe.a,{id:"group-about",className:"mb-2",label:G("DescriptionPlaceholder"),onChange:W,value:P,disabled:!o}),t.isCreator&&n.a.createElement(ve.a,{icon:"lock",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},G("GroupType")),n.a.createElement("span",{className:"subtitle"},t.username?G("TypePublic"):G("TypePrivate"))),l&&n.a.createElement(ve.a,{icon:"message",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},G("LinkedChannel")),n.a.createElement("span",{className:"subtitle"},G("DiscussionUnlink"))),n.a.createElement(ve.a,{icon:"permissions",multiline:!0,ripple:!0,onClick:$,disabled:!i},n.a.createElement("span",{className:"title"},G("ChannelPermissions")),n.a.createElement("span",{className:"subtitle"},X,"/",8)),n.a.createElement(ve.a,{icon:"admin",multiline:!0,ripple:!0,onClick:H},n.a.createElement("span",{className:"title"},G("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},Object(sa.a)(_)))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"group",multiline:!0,ripple:!0,onClick:Q},n.a.createElement("span",{className:"title"},G("GroupMembers")),n.a.createElement("span",{className:"subtitle"},Object(sa.a)(t.membersCount))),t.fullInfo&&n.a.createElement("div",{className:"ListItem narrow no-selection"},n.a.createElement(_t.a,{checked:!t.fullInfo.isPreHistoryHidden,label:G("ChatHistory"),onChange:Z,disabled:!i}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},G("DeleteMega")))),n.a.createElement(xt,{isShown:N,onClick:K,disabled:ee,ariaLabel:G("Save")},ee?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:O,onClose:C,textParts:Object(x.a)(c||!t.isCreator?G("AreYouSureDeleteAndExit"):G("AreYouSureDeleteThisChatWithGroup",t.title),["br","simple_markdown"]),confirmLabel:c||!t.isCreator?G("DeleteMega"):G("DeleteGroupForAll"),confirmHandler:J,confirmIsDestructive:!0}))}));var Lc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t),currentUserId:e.currentUserId}),(e,t)=>Object(u.l)(t,["updateChatDefaultBannedRights"]))(({onScreenSelect:e,onChatMemberSelect:t,chat:a,currentUserId:c,updateChatDefaultBannedRights:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(F.a)(),b=Object(n.m)(()=>{e(s.g.GroupRemovedUsers)},[e]),p=Object(n.m)(()=>{e(s.g.GroupUserPermissionsCreate)},[e]),g=Object(n.m)(a=>{t(a.userId,a.promotedByUserId===c),e(s.g.GroupUserPermissions)},[c,t,e]);Object(n.n)(()=>{o(a&&a.defaultBannedRights||{}),d(!1),setTimeout(()=>{u(!1)},250)},[a]);const v=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),E=Object(n.m)(()=>{a&&(u(!0),r({chatId:a.id,bannedRights:l}))},[a,l,r]),f=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.kickedMembers?a.fullInfo.kickedMembers.length:0,[a]),O=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.members?a.fullInfo.members.filter(({bannedRights:e})=>!!e):[],[a]),j=Object(n.m)(e=>{const{bannedRights:t}=e;if(!t||!a)return;const{defaultBannedRights:n}=a;return Object.keys(t).reduce((e,a)=>{if(!t[a]||n&&n[a]||"sendInline"===a||"viewMessages"===a||"sendGames"===a)return e;const c=function(e){switch(e){case"sendMessages":return"UserRestrictionsNoSend";case"sendMedia":return"UserRestrictionsNoSendMedia";case"sendStickers":return"UserRestrictionsNoSendStickers";case"embedLinks":return"UserRestrictionsNoEmbedLinks";case"sendPolls":return"UserRestrictionsNoSendPolls";case"changeInfo":return"UserRestrictionsNoChangeInfo";case"inviteUsers":return"UserRestrictionsInviteUsers";case"pinMessages":return"UserRestrictionsPinMessages";default:return}}(a);if(!c)return e;const r=h(c);return`${e}${e.length?", "+r:r}`},"")},[a,h]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},h("ChannelPermissionsHeader")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMessages",checked:!l.sendMessages,label:h("UserRestrictionsSend"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMedia",checked:!l.sendMedia,label:h("UserRestrictionsSendMedia"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:h("UserRestrictionsSendStickers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendPolls",checked:!l.sendPolls,label:h("UserRestrictionsSendPolls"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"embedLinks",checked:!l.embedLinks,label:h("UserRestrictionsEmbedLinks"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!l.inviteUsers,label:h("UserRestrictionsInviteUsers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!l.pinMessages,label:h("UserRestrictionsPinMessages"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!l.changeInfo,label:h("UserRestrictionsChangeInfo"),blocking:!0,onChange:v}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete-user",multiline:!0,ripple:!0,narrow:!0,onClick:b},n.a.createElement("span",{className:"title"},h("ChannelBlockedUsers")),n.a.createElement("span",{className:"subtitle"},f))),n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},h("PrivacyExceptions")),n.a.createElement(ve.a,{icon:"add-user",ripple:!0,onClick:p},h("ChannelAddException")),O.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable exceptions-member",ripple:!0,onClick:()=>g(e)},n.a.createElement(Ee.a,{userId:e.userId,status:j(e)}))))),n.a.createElement(xt,{isShown:i,onClick:E,ariaLabel:h("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var Ac=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,usersById:n}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,usersById:t,updateChatMemberBannedRights:a})=>{const c=Object(F.a)(),r=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.kickedMembers?e.fullInfo.kickedMembers:[],[e]),s=Object(n.m)(e=>{if(!e.kickedByUserId)return;const a=t[e.kickedByUserId];return a?c("UserRemovedBy",Object(m.Y)(a)):void 0},[c,t]),l=Object(n.m)(t=>{if(e)return[{title:c("Unblock"),icon:"delete",destructive:!0,handler:()=>a({chatId:e.id,userId:t.userId,bannedRights:{}})}]},[c,e,a]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("p",{className:"text-muted"},c("NoBlockedGroup2")),r.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,contextActions:l(e)},n.a.createElement(Ee.a,{userId:e.userId,status:s(e)}))))))}));var Tc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management;return{chat:a,progress:n,isSignaturesShown:Boolean(a&&a.isSignaturesShown),canChangeInfo:Object(m.q)(a,"changeInfo")}},(e,t)=>Object(u.l)(t,["toggleSignatures","updateChat","closeManagement","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isSignaturesShown:c,canChangeInfo:l,onScreenSelect:o,updateChat:i,toggleSignatures:d,closeManagement:u,leaveChannel:h,deleteChannel:b,openChat:p})=>{const g=t&&t.title||"",E=t&&t.fullInfo&&t.fullInfo.about||"",f=t&&t.fullInfo&&t.fullInfo.linkedChatId,[O,j,C]=Object(Ae.a)(),[y,k]=Object(n.r)(!1),[N,I]=Object(n.r)(g),[S,w]=Object(n.r)(E),[P,M]=Object(n.r)(),[A,T]=Object(n.r)(),B=t&&Object(m.f)(t),D=Object(v.a)(B,!1,r.ApiMediaFormat.BlobUrl),x=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(k(!1),T(void 0))},[a]);const U=t&&t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,R=Object(n.m)(()=>{o(s.g.ChatPrivacyType)},[o]),G=Object(n.m)(()=>{o(s.g.Discussion)},[o]),z=Object(n.m)(()=>{o(s.g.ChatAdministrators)},[o]),q=Object(n.m)(e=>{M(e),k(!0)},[]),$=Object(n.m)(e=>{I(e.target.value),k(!0)},[]),H=Object(n.m)(e=>{w(e.target.value),k(!0)},[]),V=Object(n.m)(()=>{const t=N.trim(),a=S.trim();t.length?i({chatId:e,title:t,about:a,photo:P}):T("Channel title can't be empty")},[S,e,P,N,i]),Y=Object(n.m)(()=>{d({chatId:e,isEnabled:!c})},[e,c,d]),W=Object(n.m)(()=>{o(s.g.ChannelSubscribers)},[o]),K=Object(n.m)(()=>{t.isCreator?b({chatId:t.id}):h({chatId:t.id}),C(),u(),p({id:void 0})},[t.isCreator,t.id,C,u,h,b,p]);if(t.isRestricted)return;const Q=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Dt.a,{currentAvatarBlobUrl:D,onChange:q,disabled:!l}),n.a.createElement(pe.a,{id:"channel-title",label:x("EnterChannelName"),onChange:$,value:N,error:"Channel title can't be empty"===A?A:void 0,disabled:!l}),n.a.createElement(pe.a,{id:"channel-about",className:"mb-2",label:x("DescriptionPlaceholder"),onChange:H,value:S,disabled:!l}),t.isCreator&&n.a.createElement(ve.a,{icon:"lock",ripple:!0,multiline:!0,onClick:R},n.a.createElement("span",{className:"title"},x("ChannelType")),n.a.createElement("span",{className:"subtitle"},t.username?x("TypePublic"):x("TypePrivate"))),n.a.createElement(ve.a,{icon:"message",multiline:!0,ripple:!0,onClick:G,disabled:!l},n.a.createElement("span",{className:"title"},x("Discussion")),n.a.createElement("span",{className:"subtitle"},x(f?"DiscussionUnlink":"Add"))),n.a.createElement(ve.a,{icon:"admin",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},x("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},U)),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(_t.a,{checked:c,label:x("ChannelSignMessages"),onChange:Y}))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"group",multiline:!0,ripple:!0,onClick:W},n.a.createElement("span",{className:"title"},x("ChannelSubscribers")),n.a.createElement("span",{className:"subtitle"},x("Subscribers",t.membersCount,"i")))),n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},t.isCreator?x("ChannelDelete"):x("LeaveChannel")))),n.a.createElement(xt,{isShown:y,onClick:V,disabled:Q,ariaLabel:x("Save")},Q?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:O,onClose:C,text:t.isCreator?x("ChannelDeleteAlert"):x("ChannelLeaveAlert"),confirmLabel:t.isCreator?x("ChannelDelete"):x("LeaveChannel"),confirmHandler:K,confirmIsDestructive:!0}))})),Bc=a(51);var Dc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{isUsernameAvailable:n}=Object(d.Y)(e,t);return{chat:a,isChannel:Object(m.ib)(a),progress:e.management.progress,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["checkPublicLink","updatePublicLink","updatePrivateLink"]))(({chat:e,isChannel:t,progress:a,isUsernameAvailable:c,checkPublicLink:r,updatePublicLink:l,updatePrivateLink:o})=>{const i=Boolean(e.username),d=e.fullInfo&&e.fullInfo.inviteLink,[m,u]=Object(n.r)(i?"public":"private"),[h,b]=Object(n.r)(),[p,g,v]=Object(Ae.a)(),E="public"===m&&h&&c||"private"===m&&i;Object(n.n)(()=>{m&&!d&&o()},[m,d,o]);const f=Object(n.m)(e=>{u(e)},[]),O=Object(n.m)(()=>{l({username:"public"===m?h:""})},[m,l,h]),j=Object(n.m)(()=>{v(),o()},[v,o]),C=Object(F.a)(),y=t?"Channel":"Mega",k=t?"Channel":"Group",N=[{value:"private",label:C(y+"Private"),subLabel:C(y+"PrivateInfo")},{value:"public",label:C(y+"Public"),subLabel:C(y+"PublicInfo")}],I=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading"},C(k+"Type")),n.a.createElement(ca.a,{selected:m,name:"channel-type",options:N,onChange:f})),"private"===m?n.a.createElement("div",{className:"section"},d?n.a.createElement(n.a.Fragment,null,n.a.createElement(Bc.a,{url:d,className:"group-link",text:d}),n.a.createElement("p",{className:"section-info"},C(y+"PrivateLinkHelp")),n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:g},C("RevokeLink")),n.a.createElement(Lt.a,{isOpen:p,onClose:v,text:C("RevokeAlert"),confirmLabel:C("RevokeButton"),confirmHandler:j,confirmIsDestructive:!0})):n.a.createElement(he.a,null)):n.a.createElement("div",{className:"section no-border"},n.a.createElement(zt,{asLink:!0,currentUsername:e.username,isLoading:I,isUsernameAvailable:c,checkUsername:r,onChange:b}),n.a.createElement("p",{className:"section-info"},C(k+".Username.CreatePublicLinkHelp")))),n.a.createElement(xt,{isShown:E,disabled:I,ariaLabel:C("Save"),onClick:O},I?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var xc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{forDiscussionIds:n,byId:c}=e.chats;return{chat:a,chatsByIds:c,forDiscussionIds:n,linkedChat:a&&a.fullInfo&&a.fullInfo.linkedChatId?Object(d.f)(e,a.fullInfo.linkedChatId):void 0,isChannel:a&&Object(m.ib)(a)}},(e,t)=>Object(u.l)(t,["loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup"]))(({chat:e,chatId:t,chatsByIds:a,linkedChat:c,forDiscussionIds:r,isChannel:o,onScreenSelect:i,loadGroupsForDiscussion:d,linkDiscussionGroup:m,unlinkDiscussionGroup:u})=>{const[h,b]=Object(n.r)(),[p,g]=Object(n.r)(),[v,E]=Object(n.r)(!1),f=Object(n.m)(()=>E(!0),[]),[O,j,C]=Object(Ae.a)(),[y,k,N]=Object(Ae.a)(),I=Object(F.a)(),S=c&&c.id;Object(n.n)(()=>{d()},[d]),Object(n.n)(()=>{p||Object(Ht.a)("DiscussionGroups").then(g)},[p]);const w=Object(n.m)(()=>{C(),u({channelId:o?t:S}),o||i(s.g.Initial)},[C,u,o,t,S,i]),P=Object(n.m)(()=>{N(),m({channelId:t,chatId:h})},[N,m,t,h]);function M(){const e=a[h];if(e)return n.a.createElement("div",{className:"modal-header"},n.a.createElement(U.a,{size:"tiny",chat:e}),n.a.createElement("div",{className:"modal-title"},I("Channel.DiscussionGroup.LinkGroup")))}function L(){const t=a[h];if(t)return t.hasPrivateLink?Object(x.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?`,["br","simple_markdown"]):Object(x.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?\n\nAnyone from the channel will be able to see messages in this group.`,["br","simple_markdown"])}return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("div",{className:"section-icon"},p&&n.a.createElement(Vt.a,{id:"discussionGroupsDucks",size:l.qb,animationData:p,play:v,noLoop:!0,onLoad:f})),c&&n.a.createElement("div",null,n.a.createElement(ve.a,{className:"chat-item-clickable",inactive:!0},n.a.createElement(fe.a,{chatId:c.id})),n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel")),n.a.createElement(Lt.a,{isOpen:O,onClose:C,header:n.a.createElement("div",{className:"modal-header"},n.a.createElement(U.a,{size:"tiny",chat:c}),n.a.createElement("div",{className:"modal-title"},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"))),textParts:Object(x.a)(I(o?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",c.title),["br","simple_markdown"]),confirmLabel:I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"),confirmHandler:w,confirmIsDestructive:!0})),!c&&n.a.createElement("div",null,n.a.createElement("p",{className:"section-help"},I("DiscussionChannelHelp")),n.a.createElement("div",{teactFastList:!0},n.a.createElement(ve.a,{key:"create-group",icon:"group",ripple:!0,teactOrderKey:0,className:"not-implemented"},I("DiscussionCreateGroup")),r?r.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t+1,className:"chat-item-clickable scroll-item",onClick:()=>{b(e),k()}},n.a.createElement(fe.a,{chatId:e}))):n.a.createElement(Qe.a,{key:"nothing-found",teactOrderKey:0,text:"No discussion groups found"})),n.a.createElement("p",{className:"mt-4 mb-0 section-help"},I("DiscussionChannelHelp2")),n.a.createElement(Lt.a,{isOpen:y,onClose:N,header:M(),textParts:L(),confirmLabel:I("DiscussionLinkGroup"),confirmHandler:P,isButtonsInOneRow:!0})))))}));var Uc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t);return{chat:n,isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,selectedChatMemberId:t,onScreenSelect:a,updateChatMemberBannedRights:c,isFormFullyDisabled:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),[h,b,p]=Object(Ae.a)(),g=Object(F.a)(),v=Object(n.p)(()=>{if(e&&e.fullInfo&&e.fullInfo.members)return e.fullInfo.members.find(({userId:e})=>e===t)},[e,t]);Object(n.n)(()=>{e&&e.fullInfo&&t&&!v&&a(s.g.GroupPermissions)},[e,a,v,t]),Object(n.n)(()=>{o(v&&v.bannedRights||e&&e.defaultBannedRights||{}),d(!1),u(!1)},[e,v]);const E=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),f=Object(n.m)(()=>{e&&t&&(u(!0),c({chatId:e.id,userId:t,bannedRights:l}))},[e,t,l,c]),O=Object(n.m)(()=>{e&&t&&c({chatId:e.id,userId:t,bannedRights:{viewMessages:!0}})},[e,t,c]),j=Object(n.m)(t=>!!r||!(!e||!e.defaultBannedRights)&&e.defaultBannedRights[t],[e,r]);if(v)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:v.userId})),n.a.createElement("h3",{className:"section-heading mt-4"},g("UserRestrictionsCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMessages",checked:!l.sendMessages,label:g("UserRestrictionsSend"),blocking:!0,disabled:j("sendMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendMedia",checked:!l.sendMedia,label:g("UserRestrictionsSendMedia"),blocking:!0,disabled:j("sendMedia"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:g("UserRestrictionsSendStickers"),blocking:!0,disabled:j("sendStickers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"sendPolls",checked:!l.sendPolls,label:g("UserRestrictionsSendPolls"),blocking:!0,disabled:j("sendPolls"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"embedLinks",checked:!l.embedLinks,label:g("UserRestrictionsEmbedLinks"),blocking:!0,disabled:j("embedLinks"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!l.inviteUsers,label:g("UserRestrictionsInviteUsers"),blocking:!0,disabled:j("inviteUsers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!l.pinMessages,label:g("UserRestrictionsPinMessages"),blocking:!0,disabled:j("pinMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!l.changeInfo,label:g("UserRestrictionsChangeInfo"),blocking:!0,disabled:j("changeInfo"),onChange:E}))),!r&&n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"delete-user",ripple:!0,destructive:!0,onClick:b},g("UserRestrictionsBlock")))),n.a.createElement(xt,{isShown:i,onClick:f,ariaLabel:g("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:h,onClose:p,text:"Are you sure you want to ban and remove this user from the group?",confirmLabel:"Remove",confirmHandler:O,confirmIsDestructive:!0}))}));var Rc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,currentUserId:e.currentUserId,isChannel:Object(m.ib)(a),usersById:n}})(({chat:e,isChannel:t,currentUserId:a,usersById:c,onScreenSelect:r,onChatMemberSelect:l})=>{const o=Object(F.a)();const i=Object(n.p)(()=>e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),d=Object(n.m)(e=>{l(e.userId,e.promotedByUserId===a),r(s.g.ChatAdminRights)},[a,l,r]),u=Object(n.m)(e=>{if(e.isOwner)return o("ChannelCreator");const t=e.promotedByUserId?c[e.promotedByUserId]:void 0;return t?o("EditAdminPromotedBy",Object(m.Y)(t)):o("ChannelAdmin")},[o,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{icon:"recent",multiline:!0,ripple:!0,onClick:function(){r(s.g.GroupRecentActions)}},n.a.createElement("span",{className:"title"},o("EventLog")),n.a.createElement("span",{className:"subtitle"},o(t?"EventLogInfoDetailChannel":"EventLogInfoDetail")))),n.a.createElement("div",{className:"section"},n.a.createElement("p",{className:"text-muted"},t?"You can add administrators to help you manage your channel.":"You can add administrators to help you manage your group."),i.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,onClick:()=>d(e)},n.a.createElement(Ee.a,{userId:e.userId,status:u(e),forceShowSelf:!0}))))))}));var Gc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t)}))(({chat:e})=>{const t=Object(F.a)(),a=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),c=Object(n.m)(e=>e.isOwner?t("ChannelCreator"):t("ChannelAdmin"),[t]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section not-implemented"},n.a.createElement("h3",{className:"section-heading"},"Actions"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogAllEvents"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewAdmins"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewMembers"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterChannelInfo"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterDeletedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterEditedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterLeavingMembers"),onChange:void 0}))),n.a.createElement("div",{className:"section not-implemented"},n.a.createElement("h3",{className:"section-heading"},"Admins"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!0,label:t("EventLogAllAdmins"),onChange:void 0})),a.map(e=>n.a.createElement(ve.a,{key:e.userId,className:"chat-item-clickable picker-list-item",onClick:void 0,ripple:!0},n.a.createElement(_t.a,{label:"",checked:!0}),n.a.createElement(Ee.a,{userId:e.userId,status:c(e),forceShowSelf:!0}))))))}));var zc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t),{byId:c}=e.users,{currentUserId:r}=e;return{chat:n,usersById:c,currentUserId:r,isChannel:Object(m.ib)(n),isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatAdmin"]))(({selectedChatMemberId:e,onScreenSelect:t,chat:a,usersById:c,currentUserId:r,isChannel:l,isFormFullyDisabled:o,updateChatAdmin:i})=>{const[d,u]=Object(n.r)({}),[h,b]=Object(n.r)(!1),[p,g]=Object(n.r)(!1),[v,E,f]=Object(Ae.a)(),[O,j]=Object(n.r)(""),C=Object(F.a)(),y=Object(n.p)(()=>{if(a.fullInfo&&a.fullInfo.adminMembers)return a.fullInfo.adminMembers.find(({userId:t})=>t===e)},[a,e]);Object(n.n)(()=>{a&&a.fullInfo&&e&&!y&&t(s.g.ChatAdministrators)},[a,t,y,e]),Object(n.n)(()=>{u(y&&y.adminRights||{}),j((y&&y.customTitle||"").substr(0,16)),b(!1),g(!1)},[y]);const k=Object(n.m)(e=>{const{name:t}=e.target;u(e=>{return{...e,[t]:(a=e[t],!a||void 0)};var a}),b(!0)},[]),N=Object(n.m)(()=>{e&&(g(!0),i({chatId:a.id,userId:e,adminRights:d,customTitle:O}))},[a,e,d,O,i]),I=Object(n.m)(()=>{e&&(i({chatId:a.id,userId:e,adminRights:{}}),f())},[a.id,f,e,i]),S=Object(n.m)(e=>!Object(m.hb)(a)&&(!(!o&&a.adminRights)||!a.adminRights[e]),[a,o]),w=Object(n.p)(()=>{if(!y)return;if(y.isOwner)return C("ChannelCreator");const e=y.promotedByUserId?c[y.promotedByUserId]:void 0;return e?C("EditAdminPromotedBy",Object(m.Y)(e)):C("ChannelAdmin")},[y,c,C]),P=Object(n.m)(e=>{const{value:t}=e.target;j(t),b(!0)},[]);if(y)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(ve.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Ee.a,{userId:y.userId,status:w,forceShowSelf:!0})),n.a.createElement("h3",{className:"section-heading mt-4"},C("EditAdminWhatCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"changeInfo",checked:!!d.changeInfo,label:C(l?"EditAdminChangeChannelInfo":"EditAdminChangeGroupInfo"),blocking:!0,disabled:S("changeInfo"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"postMessages",checked:!!d.postMessages,label:C("EditAdminPostMessages"),blocking:!0,disabled:S("postMessages"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"editMessages",checked:!!d.editMessages,label:C("EditAdminEditMessages"),blocking:!0,disabled:S("editMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"deleteMessages",checked:!!d.deleteMessages,label:C(l?"EditAdminDeleteMessages":"EditAdminGroupDeleteMessages"),blocking:!0,disabled:S("deleteMessages"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"banUsers",checked:!!d.banUsers,label:C("EditAdminBanUsers"),blocking:!0,disabled:S("banUsers"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"inviteUsers",checked:!!d.inviteUsers,label:C("EditAdminAddUsers"),blocking:!0,disabled:S("inviteUsers"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"pinMessages",checked:!!d.pinMessages,label:C("EditAdminPinMessages"),blocking:!0,disabled:S("pinMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"addAdmins",checked:!!d.addAdmins,label:C("EditAdminAddAdmins"),blocking:!0,disabled:S("addAdmins"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(_t.a,{name:"anonymous",checked:!!d.anonymous,label:C("EditAdminSendAnonymously"),blocking:!0,disabled:S("anonymous"),onChange:k})),o&&n.a.createElement("p",{className:"section-info mb-4"},C("Channel.EditAdmin.CannotEdit")),!l&&n.a.createElement(pe.a,{id:"admin-title",label:C("EditAdminRank"),onChange:P,value:O,disabled:o,maxLength:16}),r!==e&&!o&&n.a.createElement(ve.a,{icon:"delete",ripple:!0,destructive:!0,onClick:E},C("EditAdminRemoveAdmin")))),n.a.createElement(xt,{isShown:h,onClick:N,ariaLabel:C("Save"),disabled:p},p?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(Lt.a,{isOpen:v,onClose:f,text:"Are you sure you want to dismiss this admin?",confirmLabel:"Dismiss",confirmHandler:I,confirmIsDestructive:!0}))}));var qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.ib)(a)}},(e,t)=>Object(u.l)(t,["openUserInfo"]))(({members:e,usersById:t,isChannel:a,openUserInfo:c})=>{const r=Object(n.p)(()=>{if(e&&t)return Object(m.Cb)(e.map(({userId:e})=>e),t)},[e,t]),s=Object(n.m)(e=>{c({id:e})},[c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},r?r.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>s(e)},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(Qe.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var $c=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.ib)(a)}})(({usersById:e,members:t,isChannel:a,onScreenSelect:c,onChatMemberSelect:r})=>{const l=Object(n.p)(()=>{if(t&&e)return Object(m.Cb)(t.filter(e=>!e.isOwner).map(({userId:e})=>e),e)},[t,e]),o=Object(n.m)(e=>{r(e),c(s.g.GroupUserPermissions)},[r,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},l?l.map((e,t)=>n.a.createElement(ve.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>o(e)},n.a.createElement(Ee.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(Qe.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Hc=Object(n.h)(Object(c.h)(e=>({managementType:Object(d.u)(e)}))(({chatId:e,currentScreen:t,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r,onChatMemberSelect:l,managementType:o})=>{switch(t){case s.g.Initial:switch(o){case"user":return n.a.createElement(Mc,{key:e,userId:e});case"group":return n.a.createElement(Fc,{key:e,chatId:e,onScreenSelect:r});case"channel":return n.a.createElement(Tc,{key:e,chatId:e,onScreenSelect:r})}break;case s.g.ChatPrivacyType:return n.a.createElement(Dc,{chatId:e});case s.g.Discussion:return n.a.createElement(xc,{chatId:e,onScreenSelect:r});case s.g.GroupPermissions:return n.a.createElement(Lc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRemovedUsers:return n.a.createElement(Ac,{chatId:e});case s.g.GroupUserPermissionsCreate:return n.a.createElement($c,{chatId:e,onChatMemberSelect:l,onScreenSelect:r});case s.g.GroupUserPermissions:return n.a.createElement(Uc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChatAdministrators:return n.a.createElement(Rc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRecentActions:return n.a.createElement(Gc,{chatId:e});case s.g.ChatAdminRights:return n.a.createElement(zc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChannelSubscribers:case s.g.GroupMembers:return n.a.createElement(qc,{chatId:e})}}));const Vc={USD:"$",EUR:"€",GBP:"£",JPY:"¥",RUB:"₽",UAH:"₴",INR:"₹",AED:"د.إ"};function Yc(e){return e&&Vc[e]||""}const Wc=/^4[0-9]{12}(?:[0-9]{1,3})?$/,Kc=/^5[1-5][0-9]{11,14}$/,Qc=/^2[2-7][0-9]{11,14}$/;let Zc;!function(e){e[e.Default=0]="Default",e[e.Visa=1]="Visa",e[e.Mastercard=2]="Mastercard"}(Zc||(Zc={}));const Xc={[Zc.Default]:"",[Zc.Visa]:"visa",[Zc.Mastercard]:"mastercard"};function _c(e){return e=e.replace(/\s/g,""),Wc.test(e)?Zc.Visa:Kc.test(e)||Qc.test(e)?Zc.Mastercard:Zc.Default}var Jc=a(54);const er={streetLine1:"",streetLine2:"",city:"",state:"",countryIso2:"",postCode:"",fullName:"",email:"",phone:"",shipping:"",cardNumber:"",cardholder:"",expiry:"",cvv:"",billingCountry:"",billingZip:"",saveInfo:!0,saveCredentials:!1,formErrors:{}},tr=(e,t)=>{switch(t.type){case"changeAddress1":return{...e,streetLine1:t.payload,formErrors:{...e.formErrors,streetLine1:void 0}};case"changeAddress2":return{...e,streetLine2:t.payload,formErrors:{...e.formErrors,streetLine2:void 0}};case"changeCity":return{...e,city:t.payload,formErrors:{...e.formErrors,city:void 0}};case"changeState":return{...e,state:t.payload,formErrors:{...e.formErrors,state:void 0}};case"changeCountry":return{...e,countryIso2:t.payload,billingCountry:ar(t.payload),formErrors:{...e.formErrors,countryIso2:void 0}};case"changePostCode":return{...e,postCode:t.payload,formErrors:{...e.formErrors,postCode:void 0}};case"changeFullName":return{...e,fullName:t.payload,formErrors:{...e.formErrors,fullName:void 0}};case"changeEmail":return{...e,email:t.payload,formErrors:{...e.formErrors,email:void 0}};case"changePhone":return{...e,phone:t.payload,formErrors:{...e.formErrors,phone:void 0}};case"changeShipping":return{...e,shipping:t.payload};case"changeCardNumber":return{...e,cardNumber:t.payload,formErrors:{...e.formErrors,cardNumber:void 0}};case"changeCardholder":return{...e,cardholder:t.payload,formErrors:{...e.formErrors,cardholder:void 0}};case"changeExpiryDate":return{...e,expiry:t.payload,formErrors:{...e.formErrors,expiry:void 0}};case"changeCvvCode":return{...e,cvv:t.payload,formErrors:{...e.formErrors,cvv:void 0}};case"changeBillingCountry":return{...e,billingCountry:t.payload,formErrors:{...e.formErrors,billingCountry:void 0}};case"changeBillingZip":return{...e,billingZip:t.payload,formErrors:{...e.formErrors,billingZip:void 0}};case"changeSaveInfo":return{...e,saveInfo:t.payload};case"changeSaveCredentials":return{...e,saveCredentials:t.payload};case"updateUserInfo":return t.payload.countryIso2?{...e,...t.payload,billingCountry:ar(t.payload.countryIso2)}:{...e,...t.payload};case"setFormErrors":return{...e,formErrors:{...e.formErrors,...t.payload}};default:return e}};function ar(e){const t=Tt.a.find(({id:t})=>t===e);return t?t.name:""}function nr(e,t=400){Object(n.n)(()=>{o.k||setTimeout(()=>{Object(V.b)(()=>{e.current&&e.current.focus()})},t)},[e,t])}var cr=Object(n.h)(e=>{const{id:t,value:a,label:c,hasArrow:r,error:s,ref:l,placeholder:o,onChange:i,children:d}=e,m=s||c,u=Object(ce.a)("input-group",a&&"touched",s&&"error",m&&"with-label",r&&"with-arrow","input-group");return n.a.createElement("div",{className:u},n.a.createElement("select",{className:"form-control",id:t,value:a||"",onChange:i,placeholder:o||c,ref:l},d),m&&t&&n.a.createElement("label",{htmlFor:t},m))});a(293);var rr=Object(n.h)(({state:e,needEmail:t,needPhone:a,needName:c,needAddress:r,dispatch:s})=>{const l=Object(n.q)(null),o=Object(n.q)(null),i=Object(n.q)(null);Object(n.n)(()=>{i.current&&i.current.value!==e.countryIso2&&(i.current.value=e.countryIso2)},[e.countryIso2]);const d=Object(F.a)();nr(l);const m=Object(n.m)(e=>{s({type:"changeAddress1",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeAddress2",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeCity",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeState",payload:e.target.value})},[s]),p=Object(n.m)(e=>{s({type:"changeCountry",payload:e.target.value})},[s]),g=Object(n.m)(e=>{s({type:"changePostCode",payload:e.target.value})},[s]),v=Object(n.m)(e=>{s({type:"changeFullName",payload:e.target.value})},[s]),E=Object(n.m)(e=>{s({type:"changeEmail",payload:e.target.value})},[s]),f=Object(n.m)(e=>{let{value:t}=e.target;t="+"+t.replace(/\D/g,""),o.current&&(o.current.value=t),s({type:"changePhone",payload:t})},[s]),O=Object(n.m)(e=>{s({type:"changeSaveInfo",payload:e.target.value})},[s]),{formErrors:j}=e;return n.a.createElement("div",{className:"ShippingInfo"},n.a.createElement("form",null,r?n.a.createElement("div",null,n.a.createElement("h5",null,d("PaymentShippingAddress")),n.a.createElement(pe.a,{ref:l,label:"Address1 (Street)",onChange:m,value:e.streetLine1,inputMode:"text",error:j.streetLine1}),n.a.createElement(pe.a,{label:"Address2 (Street)",onChange:u,value:e.streetLine2,inputMode:"text",error:j.streetLine2}),n.a.createElement(pe.a,{label:"City",onChange:h,value:e.city,inputMode:"text",error:j.city}),n.a.createElement(pe.a,{label:"State",onChange:b,value:e.state,inputMode:"text",error:j.state}),n.a.createElement(cr,{label:"Country",placeholder:"Country",onChange:p,value:e.countryIso2,hasArrow:Boolean(!0),id:"shipping-country",error:j.countryIso2,ref:i},Tt.a.map(({name:e,id:t})=>n.a.createElement("option",{value:t,className:"county-item"},e))),n.a.createElement(pe.a,{label:"Post Code",onChange:g,value:e.postCode,inputMode:"text",error:j.postCode})):void 0,c||t||a?n.a.createElement("h5",null,d("PaymentShippingReceiver")):void 0,c&&n.a.createElement(pe.a,{label:"Full name",onChange:v,value:e.fullName,inputMode:"text",error:j.fullName}),t&&n.a.createElement(pe.a,{label:"Email",onChange:E,value:e.email,inputMode:"email",error:j.email}),a&&n.a.createElement(pe.a,{label:"Phone number",onChange:f,value:e.phone,inputMode:"tel",error:j.phone,ref:o}),n.a.createElement(_t.a,{label:d("PaymentShippingSave"),subLabel:d("PaymentShippingSaveInfo"),checked:Boolean(e.saveInfo),onChange:O})))});a(294);var sr=Object(n.h)(({state:e,shippingOptions:t,currency:a,dispatch:c})=>{Object(n.n)(()=>{t&&!e.shipping&&c({type:"changeShipping",payload:t[0].id})},[t,e.shipping,c]);const r=Object(n.m)(e=>{c({type:"changeShipping",payload:e})},[c]),s=Object(n.p)(()=>t.map(({id:e,title:t,amount:n})=>({label:t,subLabel:`${a} ${String(n/100)}`,value:e})),[t,a]);return n.a.createElement("div",{className:"Shipping"},n.a.createElement("form",null,n.a.createElement("p",null,"Select shipping method"),n.a.createElement(ca.a,{name:"shipping-options",options:s,onChange:r,selected:e.shipping})))});a(295);function lr(e,t,a,c=!1){return n.a.createElement("div",{className:"price-info-item "+(c?"price-info-item-main":"")},n.a.createElement("div",{className:"title"},e),n.a.createElement("div",{className:"value"},`${a||""} ${(t/100).toFixed(2)}`))}function or(e,t,a){return n.a.createElement("div",{className:"checkout-info-item"},n.a.createElement("i",{className:e}," "),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},t),n.a.createElement("p",{className:"data"},a)))}var ir=Object(n.h)(({invoiceContent:e,prices:t,shippingPrices:a,checkoutInfo:c,currency:r,totalPrice:s})=>{const{photoUrl:l,title:o,text:i}=e||{},{paymentMethod:d,paymentProvider:m,shippingAddress:u,name:h,phone:b,shippingMethod:p}=c||{};return n.a.createElement("div",{className:"Checkout"},n.a.createElement("div",{className:"description has-image"},l&&n.a.createElement("img",{src:l,alt:""}),n.a.createElement("div",{className:"text"},n.a.createElement("h5",null,o),n.a.createElement("p",null,i))),n.a.createElement("div",{className:"price-info"},t&&t.map(e=>lr(e.label,e.amount,r,!1)),a&&a.map(e=>lr(e.label,e.amount,r,!1)),void 0!==s&&lr("Total",s,r,!0)),n.a.createElement("div",{className:"invoice-info"},d&&or("icon-card",d,"Payment method"),m&&or("stripe-provider",m,"Payment provider"),u&&or("icon-location",u,"Shipping address"),h&&or("icon-user",h,"Name"),b&&or("icon-phone",b,"Phone number"),p&&or("icon-truck",p,"Shipping method")))});var dr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null),r=Object(n.m)(t=>{if("Backspace"===t.key&&"/"===e.charAt(e.length-1)){const t=e.slice(0,e.length-1);c.current&&(c.current.value=t)}},[e]),s=Object(n.m)(e=>{a(function(e){const t=(e=e.replace(/[^\d]/g,"").slice(0,4)).match(/.{1,2}/g);return t&&t[0]&&Number(t[0])>12&&(t[0]="12"),t&&t[0]&&2===t[0].length&&!t[1]&&(t[1]=""),t?t.join("/"):""}(e.target.value))},[a]);return n.a.createElement(pe.a,{label:"Expiry date",ref:c,onChange:s,onKeyDown:r,value:e,error:t,inputMode:"numeric",maxLength:5})}),mr=(a(296),a.p+"mastercard.4216118edafe23cc2dec7b8807ba4622.svg"),ur=a.p+"visa.e5a7c336e1deb4b92a636e2e053878c4.svg";var hr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null);nr(c);const[r,s]=Object(n.r)(Zc.Default);Object(n.n)(()=>{const t=_c(e);s(t)},[]);const l=Object(n.m)(e=>{const t=function(e){const t=(e=e.replace(/[^\d]/g,"")).match(/.{1,4}/g);return t?t.join(" "):""}(e.target.value),n=_c(e.target.value);s(n),a(t),c.current&&(c.current.value=t)},[a,c]),o=function(e){switch(e){case Zc.Mastercard:return n.a.createElement("img",{src:mr,alt:""});case Zc.Visa:return n.a.createElement("img",{src:ur,alt:""});default:return}}(r);return n.a.createElement("div",{className:"CardInput"},n.a.createElement("span",{className:"left-addon"},o),n.a.createElement(pe.a,{ref:c,label:"Card number",onChange:l,value:e,inputMode:"numeric",className:r?"has-left-addon":"",error:t,maxLength:23}))});a(297);var br=Object(n.h)(({state:e,canSaveCredentials:t,needCardholderName:a,needCountry:c,needZip:r,dispatch:s})=>{const l=Object(n.q)(null);Object(n.n)(()=>{l.current&&l.current.value!==e.billingCountry&&(l.current.value=e.billingCountry)},[e.billingCountry]);const o=Object(n.m)(e=>{s({type:"changeCardNumber",payload:e})},[s]),i=Object(n.m)(e=>{s({type:"changeCardholder",payload:e.target.value.toUpperCase()})},[s]),d=Object(n.m)(e=>{s({type:"changeExpiryDate",payload:e})},[s]),m=Object(n.m)(e=>{s({type:"changeCvvCode",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeBillingCountry",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeBillingZip",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeSaveCredentials",payload:e.target.value})},[s]),p=Object(F.a)(),{formErrors:g={}}=e;return n.a.createElement("div",{className:"PaymentInfo"},n.a.createElement("form",null,n.a.createElement("h5",null,p("PaymentCardTitle")),n.a.createElement(hr,{onChange:o,value:e.cardNumber,error:g.cardNumber}),a&&n.a.createElement(pe.a,{label:"Name on card",onChange:i,value:e.cardholder,inputMode:"text",error:g.cardholder}),n.a.createElement("section",{className:"inline-inputs"},n.a.createElement(dr,{value:e.expiry,onChange:d,error:g.expiry}),n.a.createElement(pe.a,{label:"CVV code",onChange:m,value:e.cvv,inputMode:"numeric",maxLength:3,error:g.cvv})),c||r?n.a.createElement("h5",null,p("PaymentBillingAddress")):void 0,c&&n.a.createElement(cr,{label:"Country",placeholder:"Country",onChange:u,value:e.billingCountry,hasArrow:Boolean(!0),id:"billing-country",error:g.billingCountry,ref:l},Tt.a.map(({name:e})=>n.a.createElement("option",{value:e,className:"county-item"},e))),r&&n.a.createElement(pe.a,{label:"Post Code",onChange:h,value:e.billingZip,inputMode:"text",error:g.billingZip}),t&&n.a.createElement(_t.a,{label:p("PaymentCardSavePaymentInformation"),checked:e.saveCredentials,onChange:b})))});a(176);var pr=Object(n.h)(Object(c.h)(e=>{const{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,invoice:r,invoiceContent:s,nativeProvider:l,nativeParams:o,passwordMissing:i,error:d}=e.payment,m=Boolean(r&&(!l||"stripe"!==l)),{needCardholderName:u,needCountry:h,needZip:b}=o||{},{nameRequested:p,phoneRequested:g,emailRequested:v,shippingAddressRequested:E,flexible:f,phoneToProvider:O,emailToProvider:j,currency:C,prices:y}=r||{};return{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,nativeProvider:l,passwordMissing:i,nameRequested:p,shippingAddressRequested:E,phoneRequested:g,emailRequested:v,flexible:f,phoneToProvider:O,emailToProvider:j,currency:C,prices:y,isProviderError:m,invoiceContent:s,needCardholderName:u,needCountry:h,needZip:b,error:d,globalErrors:e.errors}},(e,t)=>Object(u.l)(t,["validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError"]))(({isOpen:e,onClose:t,step:a,shippingOptions:c,savedInfo:r,canSaveCredentials:l,nameRequested:o,shippingAddressRequested:i,phoneRequested:d,emailRequested:m,phoneToProvider:u,emailToProvider:h,currency:b,passwordMissing:p,isProviderError:g,invoiceContent:v,nativeProvider:E,prices:f,needCardholderName:O,needCountry:j,needZip:C,error:y,globalErrors:k,validateRequestedInfo:N,sendPaymentForm:I,setPaymentStep:S,sendCredentialsInfo:w,clearPaymentError:P})=>{const[M,A]=jt(tr,er),D=Yc(b),[x,U]=Object(n.r)(!1),R=Object(F.a)();Object(n.n)(()=>{(a||y||k)&&U(!1)},[a,y,k]),Object(n.n)(()=>{if(y&&y.field)A({type:"setFormErrors",payload:{[y.field]:y.fieldError}});else if(k&&k.length){const e=Object(Jc.a)(k);A({type:"setFormErrors",payload:{...e}})}},[y,k,A]),Object(n.n)(()=>{if(r){const{name:e,phone:t,email:a,shippingAddress:n}=r;A({type:"updateUserInfo",payload:{fullName:e,phone:t&&"+"!==t.charAt(0)?"+"+t:t,email:a,...n||{}}})}},[r,A]);const G=Object(n.m)(()=>{P()},[P]),z=Object(n.p)(()=>a!==s.i.Checkout?0:function(e=[],t,a){const n=t?vr(t,a):[];let c=0;const r=e.concat(n||[]);return c=r.reduce((e,t)=>e+t.amount,c),c}(f,c,M.shipping),[a,M.shipping,f,c]),q=Object(n.p)(()=>{if(a===s.i.Checkout)return function(e,t,a){const n=`${function(e){const t=_c(e);return Xc[t]||""}(e.cardNumber)} *${e.cardNumber.slice(-4)}`,c=e.streetLine1?`${e.streetLine1}, ${e.city}, ${e.countryIso2}`:void 0,{phone:r,fullName:s}=e,l=t?gr(t,e.shipping):void 0,o=l?l.title:void 0;return{paymentMethod:n,paymentProvider:a,shippingAddress:c,name:s,phone:r,shippingMethod:o}}(M,c,E||"")},[a,M,c,E]);const $=Object(n.m)(()=>{const{saveInfo:e}=M,t=function(e){const{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s,fullName:l,phone:o,email:i}=e;return{name:l,phone:o,email:i,shippingAddress:{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s}}}(M);N({requestInfo:t,saveInfo:e})},[N,M]),H=Object(n.m)(()=>{const e=function(e){const{cardNumber:t,cardholder:a,expiry:n,cvv:c,billingCountry:r,billingZip:s}=e,[l,o]=n.split("/");return{data:{cardNumber:t,cardholder:a,expiryMonth:l,expiryYear:o,cvv:c,country:r,zip:s}}}(M);w({credentials:e})},[w,M]),V=Object(n.m)(()=>{I({shippingOptionId:M.shipping,saveCredentials:M.saveCredentials})},[I,M]),Y=Object(n.m)(e=>{S({step:e})},[S]),W=Object(n.m)(()=>{switch(U(!0),a){case s.i.ShippingInfo:return $();case s.i.Shipping:return Y(s.i.PaymentInfo);case s.i.PaymentInfo:return H();case s.i.Checkout:return V();default:return()=>{}}},[a,$,Y,H,V]),K=Object(n.p)(()=>{switch(a){case s.i.ShippingInfo:return R("PaymentShippingInfo");case s.i.Shipping:return R("PaymentShippingMethod");case s.i.PaymentInfo:return R("PaymentCardInfo");case s.i.Checkout:return R("PaymentCheckout");default:return""}},[a,R]),Q=Object(n.p)(()=>{switch(a){case s.i.Checkout:return`Pay ${D}${(z/100).toFixed(2)}`;default:return"Next Step"}},[a,z,D]);return g?n.a.createElement(be.a,{className:"error",isOpen:e,onClose:t},"Sorry, Telegram T doesn't support payments with this provider yet. Please use one of our mobile apps to do this.",n.a.createElement(B.a,{isText:!0,onClick:t},"OK")):n.a.createElement(be.a,{className:"PaymentModal",isOpen:e,onClose:t},n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null,K)),void 0!==a?n.a.createElement(T.a,{name:"slide",activeKey:a},()=>n.a.createElement("div",{className:"content custom-scroll"},function(e){switch(e){case s.i.ShippingInfo:return n.a.createElement(rr,{state:M,dispatch:A,needAddress:Boolean(i),needEmail:Boolean(m||h),needPhone:Boolean(d||u),needName:Boolean(o)});case s.i.Shipping:return n.a.createElement(sr,{state:M,dispatch:A,shippingOptions:c||[],currency:D});case s.i.PaymentInfo:return n.a.createElement(br,{state:M,dispatch:A,canSaveCredentials:Boolean(!p&&l),needCardholderName:O,needCountry:j,needZip:C});case s.i.Checkout:return n.a.createElement(ir,{prices:f,shippingPrices:M.shipping&&c?vr(c,M.shipping):void 0,totalPrice:z,invoiceContent:v,checkoutInfo:q,currency:D});default:return}}(a))):n.a.createElement("div",{className:"empty-content"},n.a.createElement(L.a,{color:"gray"})),n.a.createElement("div",{className:"footer"},n.a.createElement(B.a,{type:"submit",onClick:W,disabled:x,isLoading:x},Q)),y&&!y.field&&function(){if(y)return n.a.createElement(be.a,{className:"error",isOpen:Boolean(y),onClose:G},n.a.createElement("h4",null,y.description||"Error"),y.description||"Error",n.a.createElement(B.a,{isText:!0,onClick:P},"OK"))}())}));function gr(e,t){return e.find(({id:e})=>e===t)}function vr(e,t){const a=gr(e,t);return a?a.prices:void 0}var Er=Object(n.h)(Object(c.h)(e=>{const{receipt:t}=e.payment,{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}=t||{};return{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}})(({isOpen:e,onClose:t,prices:a,shippingPrices:c,totalAmount:r,currency:s,info:l,photoUrl:o,text:i,title:d,credentialsTitle:m,shippingMethod:u})=>{const h=Object(F.a)(),b=Yc(s),p=Object(n.p)(()=>function(e,t,a){if(!t)return{paymentMethod:e};const{shippingAddress:n}=t,c=n&&n.streetLine1?`${n.streetLine1}, ${n.city}, ${n.countryIso2}`:void 0,{phone:r,name:s}=t;return{paymentMethod:e,paymentProvider:"Stripe",shippingAddress:c,name:s,phone:r,shippingMethod:a}}(m,l,u),[l,u,m]);return n.a.createElement(be.a,{className:"PaymentModal PaymentModal-receipt",isOpen:e,onClose:t},n.a.createElement("div",null,n.a.createElement("div",{className:"header"},n.a.createElement(B.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null," ",h("PaymentReceipt")," ")),n.a.createElement("div",{className:"receipt-content custom-scroll"},n.a.createElement(ir,{prices:a,shippingPrices:c,totalPrice:r,invoiceContent:{photoUrl:o,text:i,title:d},checkoutInfo:p,currency:b}))))}))},,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){"use strict";a.d(t,"a",(function(){return s}));var n=a(4),c=a(48);const r={MonkeyIdle:a.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:a.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:a.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:a.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:a.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:a.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:a.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function s(e){const t=r[e].replace(window.location.origin,"");return c.b("file"+t,n.ApiMediaFormat.Lottie)}},,,,function(e,t,a){"use strict";var n=a(0),c=a(8),r=a(1),s=a(14),l=a(94),o=a(25),i=a(99),d=a(16);a(141);const m={type:"blob",quality:.8,format:"jpeg",circle:!1};let u,h,b;var p=Object(n.h)(({file:e,onChange:t,onClose:c})=>{const[p,g]=Object(n.r)(!1);Object(n.n)(()=>{e&&(p?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:a,offsetHeight:n}=t;b=new u(t,{enableZoom:!0,boundary:{width:a,height:n},viewport:{width:a-16,height:n-16,type:"circle"}});const c=await Object(s.a)(e);await b.bind({url:c})}catch(e){r.o&&console.error(e)}}(e):async function(){return h||(h=Promise.all([a.e(5),a.e(7)]).then(a.bind(null,304)),u=(await h).default),h}().then(()=>g(!0)))},[e,p]);const v=Object(l.a)();return n.a.createElement(i.a,{isOpen:Boolean(e),onClose:c,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},p?n.a.createElement("div",{id:"avatar-crop"}):n.a.createElement(d.a,null),n.a.createElement(o.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!b)return;const e=await b.result(m),a="string"==typeof e?e:Object(s.b)(e,"avatar.jpg");t(a)},ariaLabel:v("CropImage")},n.a.createElement("i",{className:"icon-check"})))});a(142);t.a=Object(n.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:a,onChange:r})=>{const[s,l]=Object(n.r)(),[o,i]=Object(n.r)(a);Object(n.n)(()=>{i(a)},[a]);const d=Object(c.a)(o&&"filled",t&&"disabled");return n.a.createElement("div",{className:"AvatarEditable"},n.a.createElement("label",{className:d,role:"button",tabIndex:0,title:e},n.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(l(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),n.a.createElement("i",{className:"icon-camera-add"}),o&&n.a.createElement("img",{src:o,alt:"Avatar"})),n.a.createElement(p,{file:s,onClose:function(){l(void 0)},onChange:function(e){l(void 0),r(e),o&&URL.revokeObjectURL(o),i(URL.createObjectURL(e))}}))})},,,,,,,,,function(e,t,a){},,,,,,,,,function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(116),l=a(106);a(129);const o=[0,50],i=[0,20],d=[20,0],m=r.f?c.pb:c.ob;t.a=Object(n.h)(({isPasswordVisible:e,isBig:t})=>{const[a,r]=Object(n.r)(),[u,h]=Object(n.r)(),[b,p]=Object(n.r)(!1),[g,v]=Object(n.r)(!1);Object(n.n)(()=>{a?setTimeout(()=>v(!0),2e3):Object(s.a)("MonkeyClose").then(r)},[a]),Object(n.n)(()=>{u||Object(s.a)("MonkeyPeek").then(h)},[u]);const E=Object(n.m)(()=>p(!0),[]);return n.a.createElement("div",{id:"monkey",className:t?"big":""},!b&&n.a.createElement("div",{className:"monkey-preview"}),a&&n.a.createElement(l.a,{id:"closeMonkey",size:t?c.zb:m,className:g?"hidden":"shown",animationData:a,playSegment:o,noLoop:!0,onLoad:E}),u&&n.a.createElement(l.a,{id:"peekMonkey",size:t?c.zb:m,className:g?"shown":"hidden",animationData:u,playSegment:e?i:d,noLoop:!0}))})},function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(8),l=a(25);const o=r.f?550:400;t.a=Object(n.h)(({isLoading:e=!1,isPasswordVisible:t,error:a,hint:i,placeholder:d="Password",submitLabel:m="Next",clearError:u,onChangePasswordVisibility:h,onInputChange:b,onSubmit:p})=>{const g=Object(n.q)(null),[v,E]=Object(n.r)(""),[f,O]=Object(n.r)(!1);return Object(n.n)(()=>{r.k||setTimeout(()=>{g.current.focus()},o)},[]),Object(n.n)(()=>{a&&requestAnimationFrame(()=>{g.current.focus(),g.current.select()})},[a]),n.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||f&&p(v)},autoComplete:"off"},n.a.createElement("div",{className:Object(s.a)("input-group password-input",v&&"touched",a&&"error")},n.a.createElement("input",{ref:g,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:v||"",autoComplete:"current-password",onChange:function(e){a&&u();const{target:t}=e;E(t.value),O(t.value.length>=c.X),b&&b(t.value)}}),n.a.createElement("label",null,a||i||d),n.a.createElement("div",{className:"toggle-password",onClick:function(){h(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},n.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),f&&n.a.createElement(l.a,{type:"submit",ripple:!0,isLoading:e},m))})},,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,function(e,t,a){},,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){}])]); +//# sourceMappingURL=2.07f32bea8faa762b432b.js.map \ No newline at end of file diff --git a/dist/2.28b104a90f1c1a985b2b.js.map b/dist/2.07f32bea8faa762b432b.js.map similarity index 99% rename from dist/2.28b104a90f1c1a985b2b.js.map rename to dist/2.07f32bea8faa762b432b.js.map index 84db8b4f..5f304833 100644 --- a/dist/2.28b104a90f1c1a985b2b.js.map +++ b/dist/2.07f32bea8faa762b432b.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///./src/components/mediaViewer/helpers/ghostAnimation.ts","webpack:///./src/components/mediaViewer/SenderInfo.tsx","webpack:///./src/components/mediaViewer/MediaViewerActions.tsx","webpack:///./src/components/mediaViewer/MediaViewerFooter.tsx","webpack:///./src/hooks/useFullscreen.ts","webpack:///./src/components/mediaViewer/helpers/formatFileSize.ts","webpack:///./src/components/mediaViewer/VideoPlayerControls.tsx","webpack:///./src/components/mediaViewer/VideoPlayer.tsx","webpack:///./src/components/mediaViewer/ZoomControls.tsx","webpack:///./src/components/mediaViewer/PanZoom.tsx","webpack:///./src/components/mediaViewer/MediaViewer.tsx","webpack:///./src/components/main/ForwardPicker.tsx","webpack:///./src/components/main/Errors.tsx","webpack:///./src/components/main/Notifications.tsx","webpack:///./src/components/common/CalendarModal.tsx","webpack:///./src/components/common/DeleteMessageModal.tsx","webpack:///./src/components/common/PinMessageModal.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.tsx","webpack:///./src/components/middle/DeleteSelectedMessagesModal.tsx","webpack:///./src/components/middle/MessageSelectToolbar.tsx","webpack:///./src/components/left/search/LeftSearchResultChat.tsx","webpack:///./src/components/left/search/RecentContacts.tsx","webpack:///./src/components/left/search/ChatMessage.tsx","webpack:///./src/components/left/search/DateSuggest.tsx","webpack:///./src/components/left/search/ChatResults.tsx","webpack:///./src/components/left/search/ChatMessageResults.tsx","webpack:///./src/components/left/search/helpers/createMapStateToProps.ts","webpack:///./src/components/left/search/MediaResults.tsx","webpack:///./src/components/left/search/helpers/getSenderName.ts","webpack:///./src/components/left/search/LinkResults.tsx","webpack:///./src/components/left/search/FileResults.tsx","webpack:///./src/components/left/search/AudioResults.tsx","webpack:///./src/components/left/search/LeftSearch.tsx","webpack:///./src/hooks/useReducer.ts","webpack:///./src/hooks/reducers/useFoldersReducer.ts","webpack:///./src/hooks/reducers/useTwoFaReducer.ts","webpack:///./src/components/left/settings/SettingsHeader.tsx","webpack:///./src/components/left/settings/SettingsMain.tsx","webpack:///./src/components/ui/FloatingActionButton.tsx","webpack:///./src/components/common/UsernameInput.tsx","webpack:///./src/components/left/settings/SettingsEditProfile.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersMain.tsx","webpack:///./src/components/ui/ShowMoreButton.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersEdit.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatFilters.tsx","webpack:///./src/components/left/settings/folders/SettingsFolders.tsx","webpack:///./src/components/ui/RangeSlider.tsx","webpack:///./src/components/middle/composer/StickerSetCoverAnimated.tsx","webpack:///./src/components/middle/composer/StickerSetCover.tsx","webpack:///./src/components/common/StickerButton.tsx","webpack:///./src/components/left/settings/SettingsStickerSet.tsx","webpack:///./src/components/left/settings/SettingsGeneral.tsx","webpack:///./src/util/systemFilesDialog.ts","webpack:///./src/util/colors.ts","webpack:///./src/components/left/settings/WallpaperTile.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackground.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackgroundColor.tsx","webpack:///./src/components/left/settings/SettingsNotifications.tsx","webpack:///./src/components/left/settings/SettingsPrivacy.tsx","webpack:///./src/components/left/settings/SettingsLanguage.tsx","webpack:///./src/components/left/settings/helper/privacy.ts","webpack:///./src/components/left/settings/SettingsPrivacyVisibility.tsx","webpack:///./src/components/left/settings/SettingsPrivacyActiveSessions.tsx","webpack:///./src/components/left/settings/SettingsPrivacyBlockedUsers.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEnabled.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaPassword.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaStart.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaSkippableForm.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaCongratulations.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEmailCode.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFa.tsx","webpack:///./src/components/common/Picker.tsx","webpack:///./src/components/left/settings/SettingsPrivacyVisibilityExceptionList.tsx","webpack:///./src/components/left/settings/Settings.tsx","webpack:///./src/components/left/main/ContactList.tsx","webpack:///./src/components/left/newChat/NewChatStep1.tsx","webpack:///./src/components/left/newChat/NewChatStep2.tsx","webpack:///./src/components/left/newChat/NewChat.tsx","webpack:///./src/components/left/ArchivedChats.tsx","webpack:///./src/util/scrollLock.ts","webpack:///./src/components/middle/message/helpers/copyOptions.ts","webpack:///./src/components/middle/message/MessageContextMenu.tsx","webpack:///./src/components/middle/message/ContextMenuContainer.tsx","webpack:///./src/components/common/StickerSetModal.tsx","webpack:///./src/components/middle/HeaderMenuContainer.tsx","webpack:///./src/components/middle/MobileSearch.tsx","webpack:///./src/util/isFullyVisible.ts","webpack:///./src/components/middle/composer/MentionMenu.tsx","webpack:///./src/util/findInViewport.ts","webpack:///./src/components/middle/composer/AttachmentModal.tsx","webpack:///./src/components/middle/composer/PollModal.tsx","webpack:///./src/hooks/useMouseInside.ts","webpack:///./src/components/middle/composer/EmojiButton.tsx","webpack:///./src/components/middle/composer/EmojiCategory.tsx","webpack:///./src/components/middle/composer/EmojiPicker.tsx","webpack:///./src/components/middle/composer/StickerSet.tsx","webpack:///./src/components/middle/composer/StickerPicker.tsx","webpack:///./src/components/common/GifButton.tsx","webpack:///./src/components/middle/composer/GifPicker.tsx","webpack:///./src/components/middle/composer/SymbolMenuFooter.tsx","webpack:///./src/components/middle/composer/SymbolMenu.tsx","webpack:///./src/components/middle/composer/AttachMenu.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.tsx","webpack:///./src/components/right/RightSearch.tsx","webpack:///./src/components/right/StickerSetResult.tsx","webpack:///./src/components/right/StickerSearch.tsx","webpack:///./src/components/right/GifSearch.tsx","webpack:///./src/components/right/PollAnswerResults.tsx","webpack:///./src/components/right/PollResults.tsx","webpack:///./src/components/right/management/ManageUser.tsx","webpack:///./src/components/right/management/ManageGroup.tsx","webpack:///./src/components/right/management/ManageGroupPermissions.tsx","webpack:///./src/components/right/management/ManageGroupRemovedUsers.tsx","webpack:///./src/components/right/management/ManageChannel.tsx","webpack:///./src/components/right/management/ManageChatPrivacyType.tsx","webpack:///./src/components/right/management/ManageDiscussion.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissions.tsx","webpack:///./src/components/right/management/ManageChatAdministrators.tsx","webpack:///./src/components/right/management/ManageGroupRecentActions.tsx","webpack:///./src/components/right/management/ManageGroupAdminRights.tsx","webpack:///./src/components/right/management/ManageGroupMembers.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissionsCreate.tsx","webpack:///./src/components/right/management/Management.tsx","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/components/common/helpers/detectCardType.ts","webpack:///./src/hooks/reducers/usePaymentReducer.ts","webpack:///./src/hooks/useFocusAfterAnimation.tsx","webpack:///./src/components/ui/Select.tsx","webpack:///./src/components/payment/ShippingInfo.tsx","webpack:///./src/components/payment/Shipping.tsx","webpack:///./src/components/payment/Checkout.tsx","webpack:///./src/components/payment/ExpiryInput.tsx","webpack:///./src/components/middle/helpers/inputFormatters.ts","webpack:///./src/assets/mastercard.svg","webpack:///./src/assets/visa.svg","webpack:///./src/components/payment/CardInput.tsx","webpack:///./src/components/payment/PaymentInfo.tsx","webpack:///./src/components/payment/PaymentModal.tsx","webpack:///./src/components/payment/ReceiptModal.tsx","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx"],"names":["animateOpening","hasFooter","origin","bestImageData","message","mediaEl","fromImage","getNodes","width","windowWidth","windowSize","get","mediaSize","isVideo","photo","video","webPage","getMessageContent","Boolean","getVideoDimensions","getPhotoFullDimensions","AVATAR_FULL_DIMENSIONS","availableWidth","height","availableHeight","getMediaViewerAvailableDimensions","toWidth","toHeight","calculateDimensions","toLeft","toTop","mql","window","matchMedia","MEDIA_VIEWER_MEDIA_QUERY","topOffsetRem","matches","REM","getTopOffset","top","fromTop","left","fromLeft","fromWidth","fromHeight","getBoundingClientRect","MediaViewerOrigin","SharedMedia","Album","ScheduledAlbum","SearchResult","includes","uncovered","realWidth","realHeight","size","Math","max","srcWidth","srcHeight","uncover","fromTranslateX","fromTranslateY","fromScaleX","fromScaleY","ghost","createGhost","applyStyles","transform","applyShape","document","body","classList","add","requestAnimationFrame","appendChild","style","firstChild","objectFit","remove","clearShape","setTimeout","removeChild","ANIMATION_END_DELAY","animateClosing","container","toImage","getElementById","querySelector","targetTop","el","display","rect","windowHeight","isElementInViewport","shouldFadeOut","Inline","ScheduledInline","isMessageImageFullyVisible","ProfileAvatar","opacity","source","shouldAppendProfileInfo","createElement","img","Image","src","HTMLVideoElement","poster","profileInfo","cloneNode","imageEl","messageListElement","imgOffsetTop","offsetTop","closest","id","parentElement","scrollTop","offsetHeight","element","styles","Object","assign","containerSelector","mediaSelector","MiddleHeaderAvatar","mediaEls","querySelectorAll","length","withGlobal","global","chatId","messageId","isAvatar","sender","isChatPrivate","selectUser","selectChat","selectChatMessage","selectSender","setGlobal","actions","pick","closeMediaViewer","focusMessage","handleFocusMessage","useCallback","useLang","isFromChat","senderTitle","getSenderTitle","className","onClick","Avatar","key","chat","user","renderText","formatMediaDateTime","date","MediaViewerActions","mediaData","isZoomed","fileName","onCloseMediaViewer","onForward","onZoomToggle","isVideoDownloadAllowed","setIsVideoDownloadAllowed","useState","videoMediaHash","getMessageMediaHash","undefined","videoBlobUrl","downloadProgress","useMediaWithDownloadProgress","useEffect","download","handleVideoDownloadClick","e","stopPropagation","isAllowed","lang","MenuButton","useMemo","onTrigger","isOpen","Button","round","color","ariaLabel","IS_MOBILE_SCREEN","DropdownMenu","trigger","positionX","MenuItem","icon","href","ProgressSpinner","progress","noCross","MediaViewerFooter","text","isHideable","isMultiline","setIsMultiline","footerContent","checkIsMultiline","clientHeight","handleResize","throttle","addEventListener","removeEventListener","prop","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","getBrowserFullscreenElementProp","units","bytes","number","floor","log","toFixed","stopEvent","VideoPlayerControls","bufferedProgress","currentTime","duration","fileSize","isForceVisible","isForceMobileVersion","isPlayed","isFullscreenSupported","isFullscreen","onChangeFullscreen","onPlayPause","onSeek","isVisible","setVisibility","timeout","clearTimeout","downloadedPercent","totalSize","percentagePlayed","percentageBuffered","min","step","type","onInput","value","renderSeekLine","ripple","formatMediaDuration","renderTime","formatFileSize","memo","url","isGif","posterData","posterSize","isMediaViewerOpen","noPlay","onClose","videoRef","useRef","setIsPlayed","IS_TOUCH_ENV","IS_IOS","setCurrentTime","isControlsVisible","setIsControlsVisible","setFullscreen","exitFullscreen","elRef","setIsFullscreen","useLayoutEffect","listener","listenerEnter","listenerExit","current","PLATFORM_ENV","requestFullscreen","webkitRequestFullscreen","webkitEnterFullscreen","mozRequestFullScreen","mozCancelFullScreen","webkitCancelFullScreen","webkitExitFullscreen","useFullscreenStatus","isBuffered","bufferingHandlers","useBuffering","shouldRender","shouldRenderSpinner","transitionClassNames","spinnerClassNames","useShowTransition","pause","safePlay","togglePlayState","play","useVideoCleanup","handleMouseOver","handleMouseOut","handleTimeUpdate","currentTarget","handleEnded","handleFullscreenChange","handleSeek","Number","target","toggleControls","togglePayingStateBySpace","wrapperStyle","videoStyle","onMouseOver","onMouseOut","ref","autoPlay","playsInline","loop","muted","onEnded","onTimeUpdate","join","square","isShown","onChangeZoom","prevIsShown","usePrevious","inputRef","zoomLevel","setZoomLevel","isSeeking","handleStartSeek","handleStopSeek","buildClassName","disabled","onChange","onMouseDown","onMouseUp","INITIAL_MATRIX","SCALE_VALUES","1","1.5","2","2.5","3","children","noWrap","canPan","panDeltaX","panDeltaY","onPan","tunedZoomLevel","isDragging","setIsDragging","dragData","setDragData","dx","dy","x","y","matrixData","setMatrixData","panWrapperRef","panContainerRef","newZoomLevel","newPandx","newPandy","newMatrixData","areSortedArraysEqual","oldScale","wrapper","image","wrapperRect","imageRect","newImgWidth","newImgHeight","newImgX","newImgY","calculateSafeZoneOnZoom","toString","preventDefault","newDragData","pageX","pageY","onMouseMove","deltaX","deltaY","getNewMatrixData","renderPhoto","blobUrl","imageSize","alt","draggable","Spinner","threadId","avatarOwnerId","profilePhotoIndex","mediaViewer","animationLevel","settings","byKey","senderId","avatarOwner","chatMessages","collectionIds","selectScheduledMessage","selectScheduledMessages","selectChatMessages","selectOutlyingIds","selectListedIds","currentSearch","selectCurrentMediaSearch","foundIds","resultsByType","media","openMediaViewer","openForwardMenu","animationKey","webPagePhoto","getMessageWebPagePhoto","getMessagePhoto","getMessageVideo","isWebPagePhoto","isPhoto","isFromSharedMedia","isFromSearch","slideAnimation","headerAnimation","isGhostAnimation","getMessageMediaFilename","prevSenderId","canPanZoomWrap","setCanPanZoomWrap","setIsZoomed","panDelta","setPanDelta","messageIds","getChatMediaMessageIds","selectedMediaMessageIndex","indexOf","isFirst","isLast","getMediaHash","full","photos","getChatAvatarHash","blobUrlPictogram","useMedia","ApiMediaFormat","BlobUrl","previewMediaHash","blobUrlPreview","startsWith","DataUri","fullMediaData","getMessageMediaFormat","localBlobUrl","thumbDataUri","useBlurSync","getMessageMediaThumbDataUri","photoDimensions","videoDimensions","toggle","forceUpdate","useForceUpdate","addListener","removeListener","prevMessage","prevOrigin","prevAvatarOwner","prevBestImageData","dispatchHeavyAnimationEvent","textParts","renderMessageText","timer","closeZoom","handleZoomToggle","handleZoomValue","level","canCloseZoom","close","handleFooterClick","handleForward","fromChatId","captureEscKeyListener","stopCurrentAudio","getMessageId","fromId","direction","index","selectPreviousMedia","selectNextMedia","handleKeyDown","shouldCloseOnVideo","captureEvents","excludedClosestSelector","onSwipe","SwipeDirection","Right","Left","handlePan","renderSlide","isActive","calculateMediaViewerDimensions","renderSenderInfo","ShowTransition","Transition","activeKey","name","aria-label","chats","byId","chatsById","listIds","currentUserId","activeListIds","active","archivedListIds","archived","setForwardChatId","exitForwardMode","loadMoreChats","filter","setFilter","focus","blur","chatIds","sortChatIds","getCanPostInChat","MAIN_THREAD_ID","searchWords","getChatTitle","viewportIds","getMore","useInfiniteScroll","handleFilterChange","modalHeader","InputText","placeholder","Modal","header","InfiniteScroll","items","onLoadMore","noScrollRestore","map","ListItem","PrivateChatInfo","status","userId","GroupChatInfo","Loading","getErrorHeader","error","isSlowMode","errors","dismissError","title","getReadableErrorText","isText","notifications","dismissNotification","Notification","onDismiss","WEEKDAY_LETTERS","isDisabledDay","year","month","day","minDate","maxDate","selectedDay","Date","fixedMinDate","getFullYear","getMonth","getDate","fixedMaxDate","formatInputTime","String","padStart","selectedAt","maxAt","isFutureMode","isPastMode","withTimePicker","submitButtonLabel","secondButtonLabel","onSubmit","onSecondButtonClick","now","defaultSelectedDate","selectedDate","setSelectedDate","selectedHours","setSelectedHours","getHours","selectedMinutes","setSelectedMinutes","getMinutes","currentYear","currentMonth","currentDate","shouldDisableNextMonth","shouldDisablePrevMonth","calendarGrid","grid","setFullYear","setMonth","setDate","monthStartDay","getDay","i","push","gridDate","buildCalendarGrid","handleChangeHours","replace","hours","getTime","setHours","hoursStr","handleChangeMinutes","minutes","setMinutes","minutesStr","formatMonthAndYear","d","dateCopy","letter","role","tabIndex","handleDateSelect","inputMode","formatHumanDate","formatTime","formatSubmitLabel","isSchedule","selectCurrentMessageList","canDeleteForAll","selectAllowedMessageActions","contactName","getUserFirstOrLastName","getPrivateChatUserId","willDeleteForCurrentUserOnly","isChatBasicGroup","willDeleteForAll","isChatSuperGroup","album","deleteMessages","deleteScheduledMessages","handleDeleteMessageForAll","messages","shouldDeleteForAll","handleDeleteMessageForSelf","onEnter","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","isChannel","isChatChannel","isGroup","isSuperGroup","canPinForAll","pinMessage","handlePinMessageForAll","isUnpin","handlePinMessage","isOneSide","isSilent","pinnedIds","selectPinnedIds","pinnedMessagesCount","onUnpin","selectedMessageIds","selectedMessages","selectCanDeleteSelectedMessages","selectCurrentChat","exitMessageSelectMode","messageListType","canDelete","selectedMessagesCount","selectSelectedMessagesCount","canDeleteMessages","canPost","openForwardMenuForSelectedMessages","isDeleteModalOpen","openDeleteModal","closeDeleteModal","useFlag","captureKeyboardListeners","onBackspace","onDelete","onEsc","prevSelectedMessagesCount","renderingSelectedMessagesCount","formattedMessagesCount","destructive","privateChatUserId","privateChatUser","isPinned","selectIsChatPinned","withUsername","contextActions","useChatContextActions","handleDelete","avatarSize","DeleteChatModal","runThrottled","cb","userIds","topUserIds","topPeers","usersById","users","recentlyFoundChatIds","globalSearch","onReset","loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats","topUsersRef","useHorizontalScroll","handleClick","lastSyncTime","searchQuery","mediaThumbnail","mediaBlobUrl","withOnlineStatus","isSavedMessages","isSelf","isVerified","VerifiedIcon","Link","formatPastTimeShort","getMessageSummaryText","highlight","renderMessageSummary","searchDate","onSelect","suggestions","match","formatDateToString","suggestion","latestYear","getSuggestionsFromDate","localContactIds","contactList","fetchingStatus","globalResults","localResults","globalChatIds","globalUserIds","localChatIds","localUserIds","byChatId","globalMessagesByChatId","dateSearchQuery","onSearchDateSelect","searchMessagesGlobal","setGlobalSearchChatId","shouldShowMoreLocal","setShouldShowMoreLocal","shouldShowMoreGlobal","setShouldShowMoreGlobal","handleLoadMore","LoadMoreDirection","Backwards","query","handleChatClick","handlePickerItemClick","MEMO_EMPTY_ARRAY","foundContactIds","fullName","getUserFullName","username","getTranslation","unique","foundMessages","split","sort","a","b","handleClickShowMoreLocal","handleClickShowMoreGlobal","nothingFound","noFastList","NothingFound","PickerSelectedItem","chatOrUserId","clickArg","createMapStateToProps","props","currentType","isVoice","isLoading","searchChatId","handleSelectMedia","canRenderContents","useAsyncRendering","SLIDE_TRANSITION_DURATION","isMediaGrid","isMessageList","classNames","itemSelector","Media","idPrefix","getSenderName","senderName","isChatGroup","handleMessageFocus","shouldDrawDateDivider","toYearMonth","WebLink","onMessageClick","getMessageDocument","Document","withDate","datetime","smaller","onDateClick","openAudioPlayer","handlePlayAudio","Audio","renderingFor","onPlay","TABS","GlobalSearchContent","ChatList","Links","Files","Music","Voice","CHAT_TABS","slice","TRANSITION_RENDER_COUNT","keys","currentContent","setGlobalSearchContent","setGlobalSearchDate","activeTab","setActiveTab","parseDateString","handleSwitchTab","tab","content","handleSearchDateSelect","TabList","tabs","onSwitchTab","renderCount","useReducer","reducer","initialState","reducerRef","state","setState","action","currentState","INCLUDED_CHAT_TYPES","EXCLUDED_CHAT_TYPES","INCLUDE_FILTER_FIELDS","EXCLUDE_FILTER_FIELDS","selectChatFilters","mode","selectTemp","selectedChatIds","selectedChatTypes","includedChatIds","includeFilters","folder","excludedChatIds","excludeFilters","getSuggestedFolderName","filters","values","bots","groups","channels","contacts","nonContacts","INITIAL_STATE","chatFilter","foldersReducer","payload","isTouched","omit","folderId","description","currentPassword","password","hint","email","twoFaReducer","currentScreen","editedFolderId","onSaveFilter","signOut","deleteChatFolder","isSignOutDialogOpen","setIsSignOutDialogOpen","isDeleteFolderDialogOpen","setIsDeleteFolderDialogOpen","openSignOutConfirmation","closeSignOutConfirmation","openDeleteFolderConfirmation","closeDeleteFolderConfirmation","handleSignOutMessage","handleDeleteFolderMessage","SettingsMenuButton","SettingsScreens","EditProfile","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyPhoneNumberAllowedContacts","PrivacyLastSeenAllowedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyForwardingAllowedContacts","PrivacyGroupChatsAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsDeniedContacts","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaNewPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaChangePasswordHint","TwoFaNewPasswordEmail","TwoFaRecoveryEmail","TwoFaNewPasswordEmailCode","TwoFaRecoveryEmailCode","TwoFaCongratulations","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","Folders","FoldersCreateFolder","FoldersEditFolder","FoldersIncludedChats","FoldersExcludedChats","renderHeaderContent","ConfirmDialog","confirmLabel","confirmHandler","confirmIsDestructive","currentUser","onScreenSelect","formatPhoneNumberWithCode","phoneNumber","FloatingActionButton","buttonClassName","LINK_PREFIX_REGEX","USERNAME_REGEX","runDebouncedForCheckUsername","debounce","currentUsername","asLink","isUsernameAvailable","checkUsername","setUsername","langPrefix","label","usernameSuccess","usernameError","test","handleUsernameChange","newUsername","trim","isValid","isUsernameValid","success","readOnly","profileEdit","firstName","currentFirstName","lastName","currentLastName","fullInfo","bio","currentBio","currentAvatarHash","loadCurrentUser","updateProfile","isUsernameTouched","setIsUsernameTouched","isProfileFieldsTouched","setIsProfileFieldsTouched","setError","setPhoto","setFirstName","setLastName","setBio","currentAvatarBlobUrl","ProfileEditProgress","InProgress","isUsernameError","isSaveButtonShown","Complete","handlePhotoChange","newPhoto","handleFirstNameChange","handleLastNameChange","handleBioChange","handleProfileSave","trimmedFirstName","trimmedLastName","trimmedBio","AvatarEditable","UsernameInput","runThrottledForLoadRecommended","orderedIds","orderedFolderIds","foldersById","recommended","recommendedChatFolders","chatFolders","onCreateFolder","onEditFolder","loadRecommendedChatFolders","addChatFolder","showError","animationData","setAnimationData","isAnimationLoaded","setIsAnimationLoaded","handleAnimationLoad","getAnimationData","then","handleCreateFolder","userFolders","subtitle","getFolderDescriptionText","handleCreateFolderFromRecommended","AnimatedSticker","STICKER_SIZE_FOLDER_SETTINGS","noLoop","onLoad","pill","fluid","narrow","multiline","ShowMoreButton","count","itemName","itemPluralName","ERROR_NO_TITLE","ERROR_NO_CHATS","loadedActiveChatIds","loadedArchivedChatIds","dispatch","onAddIncludedChats","onAddExcludedChats","editChatFolder","isIncludedChatsListExpanded","setIsIncludedChatsListExpanded","isExcludedChatsListExpanded","setIsExcludedChatsListExpanded","includedChatTypes","excludedChatTypes","visibleIncludedChatIds","visibleExcludedChatIds","allLoadedChatsSet","Set","loadedIncludedChatIds","findIntersectionWithSet","loadedExcludedChatIds","listType","renderChats","visibleChatIds","isExpanded","leftChatsCount","clickHandler","chatType","find","typeKey","inactive","renderChatType","event","folderUpdate","selectedIds","filterValue","onSelectedIdsChange","onSelectedChatTypesChange","onFilterChange","chatTypes","shouldMinimize","hasMaxChats","handleItemClick","newSelectedIds","splice","handleChatTypeClick","newSelectedChatTypes","selectedType","isMinimized","canClose","Checkbox","checked","isSelected","withChatType","orderedPinnedIds","archivedPinnedIds","activeChatArrays","prepareChatList","archivedChatArrays","pinnedChats","otherChats","displayedIds","newFilter","handleSelectedIdsChange","ids","handleSelectedChatTypesChange","newFilters","forEach","handleReset","handleEditFolder","handleAddIncludedChats","handleAddExcludedChats","options","range","handleChange","trackWidth","possibleValuesLength","option","STICKER_SIZE_PICKER_HEADER","stickerSet","observeIntersection","isIntersecting","useIsIntersecting","mediaHash","lottieData","Lottie","shouldRenderFullMedia","useTransitionForMedia","getFirstLetters","hasThumbnail","sticker","noAnimate","onUnfaveClick","isAnimated","localMediaHash","stickerSelector","thumbnail","dataUri","previewBlobUrl","shouldPlay","markLoaded","unmarkLoaded","canAnimatedPlay","shouldRenderThumb","shouldRenderPreview","previewTransitionClassNames","fullClassName","emoji","data-sticker-id","isLowPriority","stickers","firstSticker","STICKER_SIZE_GENERAL_SETTINGS","KEYBOARD_SEND_OPTIONS","subLabel","IS_MAC_OS","ANIMATION_LEVEL_OPTIONS","stickerSetIds","added","setIds","stickerSetsById","setsById","messageTextSize","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers","setSettingOption","loadStickerSets","loadAddedStickers","stickerSettingsRef","observe","observeIntersectionForCovers","useIntersectionObserver","rootRef","isModalOpen","openModal","closeModal","setSticker","handleAnimationLevelChange","newLevel","_","handleMessageTextSizeChange","newSize","documentElement","setProperty","handleStickerSetClick","stickerSets","installedDate","RadioGroup","selected","onCheck","isChecked","fromSticker","fileSelector","openSystemFilesDialog","accept","callback","noMultiple","setAttribute","removeAttribute","onchange","click","hex2rgb","param","parseInt","substring","rgb2hex","p0","p1","p2","rgb2hsb","r","g","h","s","v","hsb2rgb","f","p","q","t","getPatternColor","rgbColor","hue","saturation","wallpaper","slug","useBlur","isDownloadAllowed","setIsDownloadAllowed","fullMedia","wasDownloadDisabled","UPLOADING_WALLPAPER_SLUG","handleSelect","blob","fetchBlob","cacheApi","CUSTOM_BG_CACHE_NAME","isBackgroundBlurred","customBackground","loadedWallpapers","loadWallpapers","uploadWallpaper","handleFileSelect","files","handleUploadWallpaper","handleSetColor","handleResetToDefault","patternColor","DEFAULT_PATTERN_COLOR","handleWallPaperSelect","currentWallpaper","async","defaultRGB","data","rgb","canvas","context","getContext","preloadImage","naturalHeight","naturalWidth","offsetWidth","drawImage","getImageData","blockSize","getAverageColor","handleWallPaperBlurChange","isUploading","DEFAULT_HSB","PREDEFINED_COLORS","hsb2positions","hsb","rects","colorPosition","colorRect","huePosition","hueRect","positions2hsb","containerRef","colorPickerRef","huePickerRef","isFirstRunRef","setHsb","getInitialHsb","hsbRef","markIsDragging","unmarkIsDragging","rgbInput","setRgbInput","hexInput","setHexInput","rectsRef","colorCtxRef","offsetLeft","handleColorDrag","handleHueDrag","onCapture","onDrag","onRelease","withCursor","hex","hueHex","w","ctx","imgData","createImageData","pixels","col","perY","st","ed","perX","putImageData","drawColor","drawHue","handleRgbChange","rgbValue","channel","handleHexChange","hexValue","handlePredefinedColorClick","dataset","data-color","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","hasContactJoinedNotifications","loadNotificationsSettings","updateContactSignUpNotification","updateNotificationSettings","handleSettingsChange","peerType","setting","currentIsSilent","currentIsShowPreviews","isShowPreviews","handleContactNotificationChange","hasPassword","privacy","blocked","activeSessions","blockedCount","totalCount","sessionsCount","visibilityPrivacyPhoneNumber","visibility","visibilityPrivacyLastSeen","lastSeen","visibilityPrivacyProfilePhoto","profilePhoto","visibilityPrivacyForwarding","forwards","visibilityPrivacyGroupChats","chatInvite","loadPrivacySettings","loadBlockedContacts","loadAuthorizations","getVisibilityValue","languages","language","loadLanguages","selectedLanguage","setSelectedLanguage","markIsLoading","unmarkIsLoading","langCode","setLanguage","nativeName","buildOptions","loadingOption","getPrivacyKey","screen","privacySettings","allowUserIds","allowChatIds","blockUserIds","blockChatIds","setPrivacyVisibility","visibilityOptions","exceptionLists","shouldShowDenied","shouldShowAllowed","privacyKey","headerText","descriptionText","allowedContactsScreen","deniedContactsScreen","allowedCount","reduce","result","membersCount","blockCount","handleVisibilityChange","getLocation","session","region","country","getDeviceEnvironment","deviceModel","platform","systemVersion","terminateAuthorization","terminateAllAuthorizations","isConfirmTerminateAllDialogOpen","openConfirmTerminateAllDialog","closeConfirmTerminateAllDialog","handleTerminateSessionClick","hash","handleTerminateAllSessions","currentSession","isCurrent","otherSessions","renderSession","handler","dateActive","appName","ip","sessions","chatsByIds","usersByIds","blockedIds","unblockContact","handleUnblockClick","contactId","viewportOffset","isPrivate","CHAT_HEIGHT_PX","renderContact","animatedEmoji","selectAnimatedEmoji","AnimatedEmoji","expectedPassword","submitLabel","clearError","validationError","setValidationError","shouldShowPassword","setShouldShowPassword","handleSubmit","newPassword","handleClearError","PasswordMonkey","isBig","isPasswordVisible","PasswordForm","onChangePasswordVisibility","onStart","FOCUS_DELAY_TIMEOUT_MS","shouldConfirm","setValue","isConfirmShown","markIsConfirmShown","unmarkIsConfirmShown","codeLength","twoFaSettings","waitingEmailCodeLength","newValue","updatePassword","checkPassword","clearTwoFaError","updateRecoveryEmail","provideTwoFaEmailCode","clearPassword","handleStartWizard","handleNewPassword","handleNewPasswordConfirm","handleNewPasswordHint","handleNewPasswordEmail","onSuccess","handleChangePasswordCurrent","handleChangePasswordNew","handleChangePasswordConfirm","handleChangePasswordHint","handleTurnOff","handleRecoveryEmailCurrentPassword","handleRecoveryEmail","handleEmailCode","code","itemIds","filterPlaceholder","notFoundText","searchInputId","getCurrentPrivacySettings","isAllowList","setPrivacySettings","selectedContactIds","setSearchQuery","isSubmitShown","setIsSubmitShown","newSelectedContactIds","setNewSelectedContactIds","handleSelectedContactIdsChange","contactsIds","foldersState","foldersDispatch","twoFaState","twoFaDispatch","handleSaveFilter","renderCurrentSection","Main","renderCurrentSectionContent","contactIds","resultIds","sortUserIds","forceShowSelf","isSearching","selectedMemberIds","onSelectedMemberIdsChange","onNextStep","setGlobalSearchQuery","handleNextStep","creationProgress","creationError","chatCreation","memberIds","createGroupChat","createChannel","setTitle","about","setAbout","ChatCreationProgress","handleTitleChange","handleDescriptionChange","handleCreateGroup","handleCreateChannel","renderedError","RENDER_COUNT","LeftColumnContent","onContentChange","newChatMemberIds","setNewChatMemberIds","NewChannelStep2","NewGroupStep2","NewChannelStep1","NewGroupStep1","folderType","noChatsText","IGNORED_KEYS","Down","ArrowDown","Up","ArrowUp","ArrowLeft","ArrowRight","PageUp","PageDown","End","Home","Tab","preventDefaultForScrollKeys","disableScrolling","passive","ontouchmove","onkeydown","enableScrolling","getCopyLabel","hasSelection","canImageBeCopied","MessageContextMenu","anchor","canSendNow","canReschedule","canReply","canEdit","canPin","canUnpin","canForward","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","onReply","onEdit","onPin","onFaveSticker","onUnfaveSticker","onSend","onReschedule","onCloseAnimationEnd","onCopyLink","copyOptions","afterEffect","getMessageText","CLIPBOARD_ITEM_SUPPORTED","selection","getSelection","mediaLoader","copyImageToClipboard","anchorNode","parentNode","clipboardText","copyTextToClipboard","getMessageCopyOptions","getTriggerElement","getRootElement","getMenuElement","positionY","useContextMenuPosition","Menu","noOptions","isScheduled","setReplyingToId","setEditingId","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink","isMenuOpen","setIsMenuOpen","setIsDeleteModalOpen","isPinModalOpen","setIsPinModalOpen","isCalendarOpen","openCalendar","closeCalendar","closeMenu","closePinModal","handleCloseCalendar","handleReply","handleEdit","handlePin","handleUnpin","handleFaveSticker","handleUnfaveSticker","handleSelectMessage","params","childMessageIds","withShift","handleScheduledMessageSend","handleOpenCalendar","handleRescheduleMessage","scheduledAt","handleCopyLink","scheduledMaxDate","getDayStartAt","selectStickerSet","stickerSetId","loadStickers","toggleStickerSet","sendMessage","throttleMs","isDisabled","stickerSetAccessHash","isPreloadedGlobally","handleButtonClick","hasCloseButton","STICKER_SIZE_MODAL","isRestricted","isMuted","canDeleteChat","getCanDeleteChat","canSubscribe","canSearch","canMute","canLeave","onSubscribeChannel","onSearchClick","updateChatMutedState","enterMessageSelectMode","handleToggleMuteClick","handleSubscribe","handleSearch","handleSelectMessages","Portal","runDebouncedForSearch","results","selectCurrentTextSearch","setLocalTextSearchQuery","searchTextMessagesLocal","closeLocalTextSearch","searchMessagesByDate","focusedIndex","setFocusedIndex","visualViewport","mainEl","activeElement","pageTop","Array","from","input","div","contentEditable","handleMessageSearchQueryChange","newQuery","handleJumpToDate","timestamp","valueOf","handleUp","newFocusIndex","handleDown","SearchInput","isFullyVisible","viewportY1","viewportY2","y1","y2","onInsertUserName","filteredChatMembers","getSelectedIndex","newIndex","cycleRestrict","selectedMentionIndex","setSelectedMentionIndex","handleArrowKey","handleUserSelect","forceFocus","handleSelectMention","member","onUp","onDown","onTab","visibleIndexes","allElements","selectorOrElements","margin","isDense","shouldContainBottom","isFound","findInViewport","first","position","fastSmoothScroll","setItemVisible","prevChatMembers","renderedChatMembers","attachments","caption","canSuggestMembers","groupChatMembers","onCaptionUpdate","onClear","prevAttachments","renderingAttachments","isMentionMenuOpen","mentionFilter","closeMentionMenu","insertMention","mentionFilteredMembers","useMentionMenu","EDITABLE_INPUT_MODAL_ID","sendAttachments","areAllPhotos","every","mimeType","areAllVideos","isQuick","quick","renderHeader","attachment","File","filename","extension","getFileExtension","previewData","MessageInput","html","editableInputId","onUpdate","shouldSetFocus","questionInputRef","optionsListRef","solutionRef","question","setQuestion","setOptions","isAnonymous","setIsAnonymous","isMultipleAnswers","setIsMultipleAnswers","isQuizMode","setIsQuizMode","solution","setSolution","correctOption","setCorrectOption","hasErrors","setHasErrors","focusInput","solutionEl","innerHTML","addNewOption","newOptions","list","scrollHeight","scrollTo","behavior","handleCreate","questionTrimmed","optionsTrimmed","o","summary","answers","correct","isPublic","multipleChoice","quiz","entities","parseMessageInput","correctAnswers","solutionEntities","updateOption","removeOption","handleCorrectOptionChange","handleIsAnonymousChange","handleMultipleAnswersChange","handleQuizModeChange","handleKeyPress","keyCode","getQuestionError","getOptionsError","renderOptions","onKeyPress","renderQuizNoOptionError","hidden","closeTimeout","useMouseInside","menuCloseTimeout","isMouseInside","native","colons","IS_EMOJI_SUPPORTED","loading","category","allEmojis","onEmojiSelect","useOnIntersect","emojisPerRow","ceil","emojis","displayedEmoji","ICONS_BY_CATEGORY","recent","people","nature","foods","activity","places","objects","symbols","flags","categoryIntersections","emojiDataPromise","emojiRawData","emojiData","recentEmojis","addRecentEmoji","headerRef","categories","setCategories","setEmojis","activeCategoryIndex","setActiveCategoryIndex","entries","entry","intersectingWithIndexes","newLeft","HEADER_BUTTON_WIDTH","fastSmoothScrollHorizontal","allCategories","themeCategories","unshift","exec","default","uncompressEmoji","ensureEmojiData","selectCategory","categoryEl","handleEmojiSelect","MENU_TRANSITION_DURATION","containerClassName","faded","STICKER_MARGIN","loadAndPlay","onStickerSelect","onStickerUnfave","stickersPerRow","STICKER_SIZE_PICKER","stickerSetIntersections","favorite","recentStickers","favoriteStickers","addedSetIds","canSendStickers","loadRecentStickers","loadFavoriteStickers","addRecentSticker","activeSetIndex","setActiveSetIndex","areAddedLoaded","allSets","noPopulatedSets","set","stickerSetEl","handleStickerSelect","handleStickerUnfave","gif","videoData","shouldRenderVideo","preload","savedGifs","gifs","saved","canSendGifs","onGifSelect","loadSavedGifs","debounceMs","SymbolMenuTabs","SYMBOL_MENU_TAB_TITLES","SYMBOL_MENU_TAB_ICONS","Emoji","Stickers","GIFs","onRemoveSymbol","onSearchOpen","renderTabButton","handleSearchOpen","isActivated","allowedAttachmentOptions","handleMouseEnter","handleMouseLeave","fastRaf","renderContent","isFrom","onMouseEnter","onMouseLeave","noCloseOnBackdrop","onFileSelect","onPollCreate","handleQuickSelect","CONTENT_TYPES_FOR_QUICK_UPLOAD","handleDocumentSelect","canAttachMedia","canAttachPolls","autoClose","forEmoji","clearStickersForEmoji","prevStickers","displayedStickers","clickInlineButton","keyboardButtons","row","button","onSilentSend","onScheduleSend","messagesById","foundResults","senderUser","getGlobal","senderChat","forwardInfo","isChannelPost","orderBy","preloadBackwards","LastMessageMeta","selectShouldLoopStickers","isSomeModalOpen","onModalToggle","isAdded","areStickersLoaded","useOnChange","coverStickerIds","covers","otherStickers","handleAddClick","canRenderStickers","STICKER_SIZE_SEARCH","selectCurrentStickerSearch","featured","featuredIds","loadFeaturedStickers","setIsModalOpen","selectCurrentGifSearch","isChatWithBot","selectIsChatWithBot","searchMoreGifs","setGifSearchQuery","getAllowedAttachmentOptions","handleGifClick","hasResults","answer","voters","offsets","pollResults","offset","answerVote","totalVoters","loadPollOptionResults","closePollResults","prevVotersCount","votersCount","setIsLoading","areVotersLoaded","limit","shouldResetVoters","handleViewMoreClick","handleMemberClick","noStatusOrTyping","leftVotersCount","renderViewMoreButton","total","getMessagePoll","resultsByOption","buildCollectionByKey","management","updateContact","deleteUser","deleteHistory","closeManagement","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","currentIsMuted","isNotificationsEnabled","setIsNotificationsEnabled","ManagementProgress","handleNotificationChange","handleDeleteContact","lastMessage","maxId","withFullInfo","hasLinkedChannel","linkedChatId","isBasicGroup","canChangeInfo","getHasAdminRight","canBanUsers","togglePreHistoryHidden","updateChat","leaveChannel","deleteChannel","currentTitle","currentAbout","imageHash","handleClickEditType","ManagementScreens","ChatPrivacyType","handleClickDiscussion","Discussion","handleClickPermissions","GroupPermissions","handleClickAdministrators","ChatAdministrators","handleSetPhoto","file","handleAboutChange","handleUpdateGroup","trimmedTitle","trimmedAbout","handleClickMembers","GroupMembers","handleTogglePreHistory","isPreHistoryHidden","isEnabled","enabledPermissionsCount","defaultBannedRights","sendStickers","sendGifs","adminsCount","adminMembers","handleDeleteGroup","isCreator","formatInteger","onChatMemberSelect","updateChatDefaultBannedRights","permissions","setPermissions","havePermissionChanged","setHavePermissionChanged","handleRemovedUsersClick","GroupRemovedUsers","handleAddExceptionClick","GroupUserPermissionsCreate","handleExceptionMemberClick","promotedByUserId","GroupUserPermissions","handlePermissionChange","getUpdatedPermissionValue","handleSavePermissions","bannedRights","removedUsersCount","kickedMembers","exceptionMembers","members","getMemberExceptions","langKey","getLangKeyForBannedRightKey","translatedString","sendMessages","blocking","sendMedia","sendPolls","embedLinks","inviteUsers","pinMessages","changeInfo","updateChatMemberBannedRights","removedMembers","getRemovedBy","kickedByUserId","kickedByUser","getContextActions","isSignaturesShown","toggleSignatures","hasLinkedChat","handleUpdateChannel","handleToggleSignatures","handleClickSubscribers","ChannelSubscribers","handleDeleteChannel","selectManagement","checkPublicLink","updatePublicLink","updatePrivateLink","privateLink","inviteLink","privacyType","setPrivacyType","isRevokeConfirmDialogOpen","openRevokeConfirmDialog","closeRevokeConfirmDialog","canUpdate","handleOptionChange","handleSave","handleRevokePrivateLink","langPrefix1","langPrefix2","SafeLink","forDiscussionIds","linkedChat","loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup","linkedGroupId","setLinkedGroupId","isConfirmUnlinkGroupDialogOpen","openConfirmUnlinkGroupDialog","closeConfirmUnlinkGroupDialog","isConfirmLinkGroupDialogOpen","openConfirmLinkGroupDialog","closeConfirmLinkGroupDialog","handleUnlinkGroupSessions","channelId","Initial","handleLinkGroupSessions","renderLinkGroupHeader","linkedGroup","renderLinkGroupConfirmText","hasPrivateLink","STICKER_SIZE_DISCUSSION_GROUPS","teactFastList","teactOrderKey","isButtonsInOneRow","isPromotedByCurrentUser","isFormFullyDisabled","selectedChatMemberId","isBanConfirmationDialogOpen","openBanConfirmationDialog","closeBanConfirmationDialog","selectedChatMember","handleBanFromGroup","viewMessages","getControlIsDisabled","isOwner","handleAdminMemberClick","ChatAdminRights","getMemberStatus","promotedByUser","GroupRecentActions","updateChatAdmin","setIsTouched","isDismissConfirmationDialogOpen","openDismissConfirmationDialog","closeDismissConfirmationDialog","customTitle","setCustomTitle","adminRights","substr","handleDismissAdmin","memberStatus","handleCustomTitleChange","postMessages","editMessages","banUsers","addAdmins","anonymous","maxLength","openUserInfo","memberId","managementType","selectCurrentManagementType","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","VISA","MASTERCARD1","MASTERCARD2","CardType","cards","Default","Visa","Mastercard","detectCardType","cardNumber","streetLine1","streetLine2","city","countryIso2","postCode","phone","shipping","cardholder","expiry","cvv","billingCountry","billingZip","saveInfo","saveCredentials","formErrors","getBillingCountry","countryCode","countryList","useFocusAfterAnimation","animationDuration","hasArrow","labelText","htmlFor","needEmail","needPhone","needName","needAddress","phoneRef","selectCountryRef","handleAddress1Change","handleAddress2Change","handleCityChange","handleStateChange","handleCountryChange","handlePostCodeChange","handleFullNameChange","handleEmailChange","handlePhoneChange","handleSaveInfoChange","shippingOptions","handleShippingSelect","amount","renderPaymentItem","main","renderCheckoutItem","invoiceContent","prices","shippingPrices","checkoutInfo","totalPrice","photoUrl","paymentMethod","paymentProvider","shippingAddress","shippingMethod","item","expiryInputRef","charAt","parts","formatCardExpiry","onKeyDown","cardNumberRef","cardType","setCardType","newCardType","formatCardNumber","cardIcon","mastercardIconPath","visaIconPath","getCardIcon","canSaveCredentials","needCardholderName","needCountry","needZip","handleCardNumberChange","handleCardholderChange","toUpperCase","handleExpiryChange","handleCvvChange","handleBillingPostCodeChange","handleChangeSaveCredentials","savedInfo","invoice","nativeProvider","nativeParams","passwordMissing","payment","isProviderError","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","globalErrors","validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError","paymentState","paymentDispatch","currencySign","field","fieldError","getShippingError","handleErrorModalClose","PaymentStep","Checkout","shippingOption","getShippingPrices","totalPrices","concat","acc","cur","getTotalPrice","detectCardTypeText","findShippingOption","getCheckoutInfo","validateRequest","requestInfo","getRequestInfo","sendCredentials","credentials","expiryMonth","expiryYear","zip","getCredentials","sendForm","shippingOptionId","setStep","nextStep","ShippingInfo","Shipping","PaymentInfo","buttonText","cuurentStep","renderModalContent","renderError","optionId","receipt","mapedPrices","info","totalAmount","credentialsTitle","fullAddress","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","path","location","cropperResultOptions","quality","format","circle","Croppie","croppiePromise","cropper","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","enableZoom","boundary","viewport","blobToDataUri","bind","err","DEBUG","console","initCropper","ensureCroppie","croppedImg","blobToFile","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","URL","revokeObjectURL","createObjectURL","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","playSegment","onInputChange","setPassword","canSubmit","setCanSubmit","select","autoComplete","MIN_PASSWORD_LENGTH"],"mappings":"s9DAiBO,SAASA,EACdC,EAAoBC,EAA2BC,EAAuBC,GAEtE,MAAQC,QAASC,GAAcC,EAASL,EAAQE,GAChD,IAAKE,EACH,OAGF,MAAQE,MAAOC,GAAgBC,IAAWC,MAE1C,IACIC,EADAC,GAAU,EAEd,GAAIT,EAAS,CACX,MAAM,MAAEU,EAAF,MAASC,EAAT,QAAgBC,GAAYC,YAAkBb,GACpDS,EAAUK,QAAQH,GAClBH,EAAYG,EAAQI,aAAmBJ,GAAUK,YAAwBN,GAASE,EAASF,YAE3FF,EAAYS,IAId,MACEb,MAAOc,EAAgBC,OAAQC,GAC7BC,YAAkCxB,EAAWY,IACzCL,MAAOkB,EAASH,OAAQI,GAAaC,YAC3CN,EAAgBE,EAAiBZ,EAAUJ,MAAOI,EAAUW,QAExDM,GAAUpB,EAAciB,GAAW,EACnCI,EA+MR,SAAsB7B,GACpB,MAAM8B,EAAMC,OAAOC,WAAWC,KAC9B,IAAIC,EAAe,MACflC,IACFkC,GAAgBJ,EAAIK,QAAU,KAAQ,OAGxC,OAAOD,EAAeE,IAtNRC,CAAarC,IAAcuB,EAAkBG,GAAY,EAEvE,IACEY,IAAKC,EAASC,KAAMC,EAAUlC,MAAOmC,EAAWpB,OAAQqB,GACtDtC,EAAUuC,wBAEd,GAAI,CACFC,IAAkBC,YAClBD,IAAkBE,MAClBF,IAAkBG,eAClBH,IAAkBI,cAClBC,SAASjD,GAAS,CAClB,MAAMkD,EAuJV,SAAiBC,EAAmBC,EAAoBf,EAAaE,EAAcjC,EAAee,GAChG,GAAI8B,IAAcC,EAAY,CAC5B,MAAMC,EAAOC,KAAKC,IAAIjD,EAAOe,IAAW8B,EAAYC,GACpDb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apmE,EAAO7D,MAAM1H,QAAU8xE,KAChCN,GACFA,EAAcjmE,EAAO7D,UAgCnB,+BAAQmT,GAASoV,GAAQnW,GACzB,yBACEvY,UAAU,kBACVC,QA/BR,WACEkzC,GAA4BF,IA+BtB90B,KAAK,SACLC,SAAU,EACV1E,MAAM,8BAEN,uBAAG1Z,UAAWizC,EAAoB,WAAa,sBAGlDk9B,GACC,kBAAC,IAAD,CAAQlqE,KAAK,SAASI,QAAM,EAACqiB,UAAWA,GACrC4pB,O","file":"2.28b104a90f1c1a985b2b.js","sourcesContent":["import { ApiMessage } from '../../../api/types';\nimport { MediaViewerOrigin } from '../../../types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { getMessageContent, getPhotoFullDimensions, getVideoDimensions } from '../../../modules/helpers';\nimport {\n AVATAR_FULL_DIMENSIONS,\n calculateDimensions,\n getMediaViewerAvailableDimensions,\n MEDIA_VIEWER_MEDIA_QUERY,\n REM,\n} from '../../common/helpers/mediaDimensions';\n\nimport windowSize from '../../../util/windowSize';\n\nconst ANIMATION_DURATION = 200;\n\nexport function animateOpening(\n hasFooter: boolean, origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage,\n) {\n const { mediaEl: fromImage } = getNodes(origin, message);\n if (!fromImage) {\n return;\n }\n\n const { width: windowWidth } = windowSize.get();\n\n let isVideo = false;\n let mediaSize;\n if (message) {\n const { photo, video, webPage } = getMessageContent(message);\n isVideo = Boolean(video);\n mediaSize = video ? getVideoDimensions(video)! : getPhotoFullDimensions((photo || webPage!.photo)!)!;\n } else {\n mediaSize = AVATAR_FULL_DIMENSIONS;\n }\n\n // eslint-disable-next-line max-len\n const {\n width: availableWidth, height: availableHeight,\n } = getMediaViewerAvailableDimensions(hasFooter, isVideo);\n const { width: toWidth, height: toHeight } = calculateDimensions(\n availableWidth, availableHeight, mediaSize.width, mediaSize.height,\n );\n const toLeft = (windowWidth - toWidth) / 2;\n const toTop = getTopOffset(hasFooter) + (availableHeight - toHeight) / 2;\n\n let {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n const uncovered = uncover(toWidth, toHeight, fromTop, fromLeft, fromWidth, fromHeight);\n fromTop = uncovered.top;\n fromLeft = uncovered.left;\n fromWidth = uncovered.width;\n fromHeight = uncovered.height;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n const fromScaleX = fromWidth / toWidth;\n const fromScaleY = fromHeight / toHeight;\n\n const ghost = createGhost(bestImageData || fromImage);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n applyShape(ghost, origin);\n\n document.body.classList.add('ghost-animating');\n\n requestAnimationFrame(() => {\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n clearShape(ghost);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n document.body.removeChild(ghost);\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nexport function animateClosing(origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage) {\n const { container, mediaEl: toImage } = getNodes(origin, message);\n if (!toImage) {\n return;\n }\n\n const fromImage = document.getElementById('MediaViewer')!.querySelector(\n '.active .media-viewer-content img, .active .media-viewer-content video',\n );\n if (!fromImage || !toImage) {\n return;\n }\n\n const {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n const {\n top: targetTop, left: toLeft, width: toWidth, height: toHeight,\n } = toImage.getBoundingClientRect();\n\n let toTop = targetTop;\n if (!isElementInViewport(container)) {\n const { height: windowHeight } = windowSize.get();\n toTop = targetTop < fromTop ? -toHeight : windowHeight;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n let fromScaleX = fromWidth / toWidth;\n let fromScaleY = fromHeight / toHeight;\n\n const shouldFadeOut = (\n [MediaViewerOrigin.Inline, MediaViewerOrigin.ScheduledInline].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n ) || (\n [MediaViewerOrigin.Album, MediaViewerOrigin.ScheduledAlbum].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n );\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n if (fromScaleX > fromScaleY) {\n fromScaleX = fromScaleY;\n } else if (fromScaleY > fromScaleX) {\n fromScaleY = fromScaleX;\n }\n }\n\n const ghost = createGhost(bestImageData || toImage, origin === MediaViewerOrigin.ProfileAvatar);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n\n requestAnimationFrame(() => {\n document.body.classList.add('ghost-animating');\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n if (shouldFadeOut) {\n ghost.style.opacity = '0';\n }\n\n applyShape(ghost, origin);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n document.body.removeChild(ghost);\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nfunction createGhost(source: string | HTMLImageElement | HTMLVideoElement, shouldAppendProfileInfo = false) {\n const ghost = document.createElement('div');\n ghost.classList.add('ghost');\n\n const img = new Image();\n\n if (typeof source === 'string') {\n img.src = source;\n } else if (source instanceof HTMLVideoElement) {\n img.src = source.poster;\n } else {\n img.src = source.src;\n }\n\n ghost.appendChild(img);\n\n if (shouldAppendProfileInfo) {\n ghost.classList.add('ProfileInfo');\n const profileInfo = document.querySelector('#RightColumn .ProfileInfo .info');\n if (profileInfo) {\n ghost.appendChild(profileInfo.cloneNode(true));\n }\n }\n\n return ghost;\n}\n\nfunction uncover(realWidth: number, realHeight: number, top: number, left: number, width: number, height: number) {\n if (realWidth === realHeight) {\n const size = Math.max(width, height) * (realWidth / realHeight);\n left -= (size - width) / 2;\n top -= (size - height) / 2;\n width = size;\n height = size;\n } else if (realWidth > realHeight) {\n const srcWidth = width;\n width = height * (realWidth / realHeight);\n left -= (width - srcWidth) / 2;\n } else if (realHeight > realWidth) {\n const srcHeight = height;\n height = width * (realHeight / realWidth);\n top -= (height - srcHeight) / 2;\n }\n\n return {\n top, left, width, height,\n };\n}\n\nfunction isElementInViewport(el: HTMLElement) {\n if (el.style.display === 'none') {\n return false;\n }\n\n const rect = el.getBoundingClientRect();\n const { height: windowHeight } = windowSize.get();\n\n return (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n}\n\nfunction isMessageImageFullyVisible(container: HTMLElement, imageEl: HTMLElement) {\n const messageListElement = document.querySelector('.active > .MessageList')!;\n let imgOffsetTop = container.offsetTop + imageEl.closest('.content-inner, .WebPage')!.offsetTop;\n if (container.id.includes('album-media-')) {\n imgOffsetTop += container.parentElement!.offsetTop + container.closest('.Message')!.offsetTop;\n }\n\n return imgOffsetTop > messageListElement.scrollTop\n && imgOffsetTop + imageEl.offsetHeight < messageListElement.scrollTop + messageListElement.offsetHeight;\n}\n\nfunction getTopOffset(hasFooter: boolean) {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n let topOffsetRem = 4.125;\n if (hasFooter) {\n topOffsetRem += mql.matches ? 0.875 : 3.375;\n }\n\n return topOffsetRem * REM;\n}\n\nfunction applyStyles(element: HTMLElement, styles: Record) {\n Object.assign(element.style, styles);\n}\n\nfunction getNodes(origin: MediaViewerOrigin, message?: ApiMessage) {\n let containerSelector;\n let mediaSelector;\n\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n containerSelector = `.active > .MessageList #album-media-${message!.id}`;\n mediaSelector = '.full-media';\n break;\n\n case MediaViewerOrigin.SharedMedia:\n containerSelector = `#shared-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.SearchResult:\n containerSelector = `#search-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n containerSelector = '.MiddleHeader .ChatInfo .Avatar';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ProfileAvatar:\n containerSelector = '#RightColumn .ProfileInfo .active .ProfilePhoto';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ScheduledInline:\n case MediaViewerOrigin.Inline:\n default:\n containerSelector = `.active > .MessageList #message${message!.id}`;\n mediaSelector = '.message-content .full-media, .message-content .thumbnail';\n }\n\n const container = document.querySelector(containerSelector)!;\n const mediaEls = container && container.querySelectorAll(mediaSelector);\n\n return {\n container,\n mediaEl: mediaEls && mediaEls[mediaEls.length - 1],\n };\n}\n\nfunction applyShape(ghost: HTMLDivElement, origin: MediaViewerOrigin) {\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n case MediaViewerOrigin.Inline:\n case MediaViewerOrigin.ScheduledInline:\n ghost.classList.add('rounded-corners');\n break;\n\n case MediaViewerOrigin.SharedMedia:\n case MediaViewerOrigin.ProfileAvatar:\n case MediaViewerOrigin.SearchResult:\n (ghost.firstChild as HTMLElement).style.objectFit = 'cover';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n ghost.classList.add('circle');\n break;\n }\n}\n\nfunction clearShape(ghost: HTMLDivElement) {\n (ghost.firstChild as HTMLElement).style.objectFit = 'default';\n ghost.classList.remove('rounded-corners', 'circle');\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../api/types';\n\nimport { getSenderTitle, isChatPrivate } from '../../modules/helpers';\nimport { formatMediaDateTime } from '../../util/dateFormat';\nimport renderText from '../common/helpers/renderText';\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from '../common/Avatar';\n\nimport './SenderInfo.scss';\n\ntype OwnProps = {\n chatId?: number;\n messageId?: number;\n isAvatar?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst SenderInfo: FC = ({\n chatId, messageId, sender, isAvatar, message, closeMediaViewer, focusMessage,\n}) => {\n const handleFocusMessage = useCallback(() => {\n closeMediaViewer();\n focusMessage({ chatId, messageId });\n }, [chatId, focusMessage, messageId, closeMediaViewer]);\n\n useLang();\n\n if (!sender || (!message && !isAvatar)) {\n return undefined;\n }\n\n const isFromChat = sender.id < 0;\n const senderTitle = getSenderTitle(sender);\n\n return (\n
\n {isFromChat ? (\n \n ) : (\n \n )}\n
\n
\n {senderTitle && renderText(senderTitle)}\n
\n
\n {isAvatar ? 'Profile photo' : formatMediaDateTime(message!.date * 1000)}\n
\n
\n
\n );\n};\n\nexport default withGlobal(\n (global, { chatId, messageId, isAvatar }): StateProps => {\n if (isAvatar && chatId) {\n return {\n sender: isChatPrivate(chatId) ? selectUser(global, chatId) : selectChat(global, chatId),\n };\n }\n\n if (!messageId || !chatId) {\n return {};\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n message,\n sender: message && selectSender(global, message),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['closeMediaViewer', 'focusMessage']),\n)(SenderInfo);\n","import React, {\n FC, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport download from '../../util/download';\nimport { getMessageMediaHash } from '../../modules/helpers';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './MediaViewerActions.scss';\n\ntype OwnProps = {\n mediaData?: string;\n isVideo: boolean;\n isZoomed: boolean;\n message?: ApiMessage;\n fileName?: string;\n isAvatar?: boolean;\n onCloseMediaViewer: NoneToVoidFunction;\n onForward: NoneToVoidFunction;\n onZoomToggle: NoneToVoidFunction;\n};\n\nconst MediaViewerActions: FC = ({\n mediaData,\n isVideo,\n isZoomed,\n message,\n fileName,\n isAvatar,\n onCloseMediaViewer,\n onForward,\n onZoomToggle,\n}) => {\n const [isVideoDownloadAllowed, setIsVideoDownloadAllowed] = useState(false);\n const videoMediaHash = isVideo && message ? getMessageMediaHash(message, 'download') : undefined;\n const {\n mediaData: videoBlobUrl, downloadProgress,\n } = useMediaWithDownloadProgress(videoMediaHash, !isVideoDownloadAllowed);\n\n // Download with browser when fully loaded\n useEffect(() => {\n if (isVideoDownloadAllowed && videoBlobUrl) {\n download(videoBlobUrl, fileName!);\n setIsVideoDownloadAllowed(false);\n }\n }, [fileName, videoBlobUrl, isVideoDownloadAllowed]);\n\n // Cancel download on slide change\n useEffect(() => {\n setIsVideoDownloadAllowed(false);\n }, [videoMediaHash]);\n\n const handleVideoDownloadClick = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setIsVideoDownloadAllowed((isAllowed) => !isAllowed);\n }, []);\n\n const lang = useLang();\n\n const MenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n if (IS_MOBILE_SCREEN) {\n return (\n
\n \n {!isAvatar && (\n \n {lang('Forward')}\n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? `${Math.round(downloadProgress * 100)}% Downloading...` : 'Download'}\n \n ) : (\n \n {lang('AccActionDownload')}\n \n )}\n \n {isVideoDownloadAllowed && }\n
\n );\n }\n\n return (\n
\n {!isAvatar && (\n <>\n \n \n \n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? (\n \n ) : (\n \n )}\n \n ) : (\n \n \n \n )}\n \n \n \n \n \n \n
\n );\n};\n\nexport default MediaViewerActions;\n","import React, { FC, useEffect, useState } from '../../lib/teact/teact';\nimport { throttle } from '../../util/schedulers';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport { REM } from '../common/helpers/mediaDimensions';\n\nimport './MediaViewerFooter.scss';\n\nconst RESIZE_THROTTLE_MS = 500;\n\ntype OwnProps = {\n text: TextPart | TextPart[];\n onClick: () => void;\n isHideable: boolean;\n};\n\nconst MediaViewerFooter: FC = ({ text = '', isHideable, onClick }) => {\n const [isMultiline, setIsMultiline] = useState(false);\n useEffect(() => {\n const footerContent = document.querySelector('.MediaViewerFooter .media-text') as HTMLDivElement | null;\n\n const checkIsMultiline = () => {\n const height = footerContent ? footerContent.clientHeight : 0;\n\n setIsMultiline(height > REM * 2);\n };\n\n // First run for initial detection of multiline footer text\n checkIsMultiline();\n\n const handleResize = throttle(checkIsMultiline, RESIZE_THROTTLE_MS, true);\n\n window.addEventListener('resize', handleResize, false);\n\n return () => {\n window.removeEventListener('resize', handleResize, false);\n };\n }, []);\n\n function stopEvent(e: React.MouseEvent) {\n if (text) {\n e.stopPropagation();\n }\n }\n\n return (\n
\n {text && (\n
\n

{text}

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

Sorry, nothing found.

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

{getReadableErrorText(error)}

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

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

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

{lang('AreYouSureDeleteSingleMessage')}

\n {willDeleteForCurrentUserOnly && (\n

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

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

This will delete it for everyone in this chat.

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

{lang('PinMessageAlertTitle')}

\n
\n );\n }\n\n function renderMessage() {\n if (isChannel) {\n return

{lang('PinMessageAlertChannel')}

;\n }\n\n if (isGroup || isSuperGroup) {\n return

{lang('PinMessageAlert')}

;\n }\n\n return

{lang('PinMessageAlertChat')}

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

{lang('UnpinAllMessages')}

\n
\n );\n }\n\n function renderMessage() {\n return

Do you want to unpin all {pinnedMessagesCount} messages in this chat?

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

{lang('AreYouSureDeleteFewMessages')}

\n {willDeleteForCurrentUserOnly && (\n

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

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

This will delete them for everyone in this chat.

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

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

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

{renderText(getChatTitle(chat, privateChatUser))}

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

\n {localResults.length > LESS_LIST_ITEMS_AMOUNT && (\n {shouldShowMoreLocal ? 'Show less' : 'Show more'}\n )}\n Contacts and Chats\n

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

\n {globalResults.length > LESS_LIST_ITEMS_AMOUNT && (\n {shouldShowMoreGlobal ? 'Show less' : 'Show more'}\n )}\n Global Search\n

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

{lang('SearchMessages')}

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

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

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

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

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

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

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

{lang('EditProfile')}

;\n case SettingsScreens.General:\n return

{lang('General')}

;\n case SettingsScreens.Notifications:\n return

{lang('Notifications')}

;\n case SettingsScreens.Privacy:\n return

{lang('PrivacySettings')}

;\n case SettingsScreens.Language:\n return

{lang('Language')}

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

{lang('ChatBackground')}

;\n case SettingsScreens.GeneralChatBackgroundColor:\n return

{lang('SetColor')}

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

{lang('PrivacyPhone')}

;\n case SettingsScreens.PrivacyLastSeen:\n return

{lang('PrivacyLastSeen')}

;\n case SettingsScreens.PrivacyProfilePhoto:\n return

{lang('Privacy.ProfilePhoto')}

;\n case SettingsScreens.PrivacyForwarding:\n return

{lang('PrivacyForwards')}

;\n case SettingsScreens.PrivacyGroupChats:\n return

{lang('AutodownloadGroupChats')}

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

{lang('AlwaysShareWith')}

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

{lang('NeverShareWith')}

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

{lang('SessionsTitle')}

;\n case SettingsScreens.PrivacyBlockedUsers:\n return

{lang('BlockedUsers')}

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

{lang('TwoStepVerification')}

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

{lang('EnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return

{lang('PleaseReEnterPassword')}

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

{lang('PasswordHint')}

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

{lang('RecoveryEmailTitle')}

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

Recovery Email Code

;\n case SettingsScreens.TwoFaCongratulations:\n return

{lang('TwoStepVerificationPasswordSet')}

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

{lang('PleaseEnterCurrentPassword')}

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

{lang('Filters')}

;\n case SettingsScreens.FoldersCreateFolder:\n return

{lang('FilterNew')}

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

{lang('FilterEdit')}

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

{lang('FilterInclude')}

\n ) : (\n

{lang('FilterExclude')}

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

{lang('SETTINGS')}

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

{getUserFullName(currentUser)}

\n

{formatPhoneNumberWithCode(currentUser.phoneNumber)}

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

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

\n
\n\n
\n

{lang('Username')}

\n\n \n\n

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

\n {username && (\n

\n This link opens a chat with you:
\n https://t.me/{username}\n

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

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

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

{lang('Filters')}

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

\n You have no folders yet.\n

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

{lang('FilterRecommended')}

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

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

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

\n {state.error}\n

\n )}\n\n

{lang('FilterInclude')}

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

{lang('FilterExclude')}

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

{lang(type.title)}

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

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

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

{lang('FilterChatTypes')}

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

{lang('FilterChats')}

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

Sorry, nothing found.

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

{lang('SETTINGS')}

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

\n Animation Level\n

\n

Choose the desired animations amount.

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

{lang('Keyboard')}

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

{lang('AutoDownloadMedia')}

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

{lang('AutoplayMedia')}

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

{lang('AccDescrStickers')}

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

{lang('AutodownloadPrivateChats')}

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

{lang('FilterGroups')}

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

{lang('FilterChannels')}

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

{lang('PhoneOther')}

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

{lang('PrivacyTitle')}

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

{headerText}

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

{descriptionText}

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

{lang('PrivacyExceptions')}

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

{lang('AuthSessions.CurrentSession')}

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

Other Sessions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{lang('GroupAddMembers')}

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

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

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

{lang('DescriptionInfo')}

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

{renderedError}

\n )}\n\n

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

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

{lang('ArchivedChats')}

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

\n Please choose the correct answer\n

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

Options

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

Solution

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

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

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

{stickerSet.title}

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

{title && renderText(title)}

\n \n
\n
\n {renderText(text, ['emoji', 'highlight'], { highlight: query })}\n
\n
\n
\n );\n };\n\n return (\n \n

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

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

{set.title}

\n

{set.count} stickers

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

Nothing found.

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

{lang('NoGIFsFound')}

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

{summary.question}

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

{lang('ChannelPermissionsHeader')}

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

{lang('PrivacyExceptions')}

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

{lang('NoBlockedGroup2')}

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

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

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

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

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

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

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

{lang('DiscussionChannelHelp')}

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

{lang('DiscussionChannelHelp2')}

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

{lang('UserRestrictionsCanDo')}

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

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

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

Actions

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

Admins

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

{lang('EditAdminWhatCanDo')}

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

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

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

Select shipping method

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

{ text }

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

\n { data }\n

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

{error.description || 'Error'}

\n {error.description || 'Error'}\n \n OK\n \n
\n );\n }\n\n function renderModalContent(cuurentStep: PaymentStep) {\n switch (cuurentStep) {\n case PaymentStep.ShippingInfo:\n return (\n \n );\n case PaymentStep.Shipping:\n return (\n \n );\n case PaymentStep.PaymentInfo:\n return (\n \n );\n case PaymentStep.Checkout:\n return (\n \n );\n default:\n return undefined;\n }\n }\n\n const validateRequest = useCallback(() => {\n const { saveInfo } = paymentState;\n const requestInfo = getRequestInfo(paymentState);\n validateRequestedInfo({ requestInfo, saveInfo });\n }, [validateRequestedInfo, paymentState]);\n\n const sendCredentials = useCallback(() => {\n const credentials = getCredentials(paymentState);\n sendCredentialsInfo({\n credentials,\n });\n }, [sendCredentialsInfo, paymentState]);\n\n const sendForm = useCallback(() => {\n sendPaymentForm({\n shippingOptionId: paymentState.shipping,\n saveCredentials: paymentState.saveCredentials,\n });\n }, [sendPaymentForm, paymentState]);\n\n const setStep = useCallback((nextStep) => {\n setPaymentStep({ step: nextStep });\n }, [setPaymentStep]);\n\n const handleButtonClick = useCallback(() => {\n setIsLoading(true);\n switch (step) {\n case PaymentStep.ShippingInfo:\n return validateRequest();\n case PaymentStep.Shipping:\n return setStep(PaymentStep.PaymentInfo);\n case PaymentStep.PaymentInfo:\n return sendCredentials();\n case PaymentStep.Checkout:\n return sendForm();\n default:\n return () => {};\n }\n }, [step, validateRequest, setStep, sendCredentials, sendForm]);\n\n const modalHeader = useMemo(() => {\n switch (step) {\n case PaymentStep.ShippingInfo:\n return lang('PaymentShippingInfo');\n case PaymentStep.Shipping:\n return lang('PaymentShippingMethod');\n case PaymentStep.PaymentInfo:\n return lang('PaymentCardInfo');\n case PaymentStep.Checkout:\n return lang('PaymentCheckout');\n default:\n return '';\n }\n }, [step, lang]);\n\n const buttonText = useMemo(() => {\n switch (step) {\n case PaymentStep.Checkout:\n return `Pay ${currencySign}${(totalPrice / 100).toFixed(2)}`;\n default:\n return 'Next Step';\n }\n }, [step, totalPrice, currencySign]);\n\n if (isProviderError) {\n return (\n \n Sorry, Telegram T doesn't support payments with this provider yet.\n Please use one of our mobile apps to do this.\n \n OK\n \n \n );\n }\n\n return (\n \n
\n \n \n \n

{ modalHeader }

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

{lang('PaymentReceipt')}

\n
\n
\n \n
\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { receipt } = global.payment;\n const {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n } = (receipt || {});\n\n return {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n };\n },\n)(ReceiptModal));\n\nfunction getCheckoutInfo(paymentMethod?: string,\n info?:\n { phone?: string;\n name?: string;\n shippingAddress?: ApiShippingAddress;\n },\n shippingMethod?: string) {\n if (!info) {\n return { paymentMethod };\n }\n const { shippingAddress } = info;\n const fullAddress = shippingAddress && shippingAddress.streetLine1\n ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}`\n : undefined;\n const { phone, name } = info;\n return {\n paymentMethod,\n paymentProvider: 'Stripe',\n shippingAddress: fullAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n
\n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///./src/components/mediaViewer/helpers/ghostAnimation.ts","webpack:///./src/components/mediaViewer/SenderInfo.tsx","webpack:///./src/components/mediaViewer/MediaViewerActions.tsx","webpack:///./src/components/mediaViewer/MediaViewerFooter.tsx","webpack:///./src/hooks/useFullscreen.ts","webpack:///./src/components/mediaViewer/helpers/formatFileSize.ts","webpack:///./src/components/mediaViewer/VideoPlayerControls.tsx","webpack:///./src/components/mediaViewer/VideoPlayer.tsx","webpack:///./src/components/mediaViewer/ZoomControls.tsx","webpack:///./src/components/mediaViewer/PanZoom.tsx","webpack:///./src/components/mediaViewer/MediaViewer.tsx","webpack:///./src/components/main/ForwardPicker.tsx","webpack:///./src/components/main/Errors.tsx","webpack:///./src/components/main/Notifications.tsx","webpack:///./src/components/common/CalendarModal.tsx","webpack:///./src/components/common/DeleteMessageModal.tsx","webpack:///./src/components/common/PinMessageModal.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.tsx","webpack:///./src/components/middle/DeleteSelectedMessagesModal.tsx","webpack:///./src/components/middle/MessageSelectToolbar.tsx","webpack:///./src/components/left/search/LeftSearchResultChat.tsx","webpack:///./src/components/left/search/RecentContacts.tsx","webpack:///./src/components/left/search/ChatMessage.tsx","webpack:///./src/components/left/search/DateSuggest.tsx","webpack:///./src/components/left/search/ChatResults.tsx","webpack:///./src/components/left/search/ChatMessageResults.tsx","webpack:///./src/components/left/search/helpers/createMapStateToProps.ts","webpack:///./src/components/left/search/MediaResults.tsx","webpack:///./src/components/left/search/helpers/getSenderName.ts","webpack:///./src/components/left/search/LinkResults.tsx","webpack:///./src/components/left/search/FileResults.tsx","webpack:///./src/components/left/search/AudioResults.tsx","webpack:///./src/components/left/search/LeftSearch.tsx","webpack:///./src/hooks/useReducer.ts","webpack:///./src/hooks/reducers/useFoldersReducer.ts","webpack:///./src/hooks/reducers/useTwoFaReducer.ts","webpack:///./src/components/left/settings/SettingsHeader.tsx","webpack:///./src/components/left/settings/SettingsMain.tsx","webpack:///./src/components/ui/FloatingActionButton.tsx","webpack:///./src/components/common/UsernameInput.tsx","webpack:///./src/components/left/settings/SettingsEditProfile.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersMain.tsx","webpack:///./src/components/ui/ShowMoreButton.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersEdit.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatFilters.tsx","webpack:///./src/components/left/settings/folders/SettingsFolders.tsx","webpack:///./src/components/ui/RangeSlider.tsx","webpack:///./src/components/middle/composer/StickerSetCoverAnimated.tsx","webpack:///./src/components/middle/composer/StickerSetCover.tsx","webpack:///./src/components/common/StickerButton.tsx","webpack:///./src/components/left/settings/SettingsStickerSet.tsx","webpack:///./src/components/left/settings/SettingsGeneral.tsx","webpack:///./src/util/systemFilesDialog.ts","webpack:///./src/util/colors.ts","webpack:///./src/components/left/settings/WallpaperTile.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackground.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackgroundColor.tsx","webpack:///./src/components/left/settings/SettingsNotifications.tsx","webpack:///./src/components/left/settings/SettingsPrivacy.tsx","webpack:///./src/components/left/settings/SettingsLanguage.tsx","webpack:///./src/components/left/settings/helper/privacy.ts","webpack:///./src/components/left/settings/SettingsPrivacyVisibility.tsx","webpack:///./src/components/left/settings/SettingsPrivacyActiveSessions.tsx","webpack:///./src/components/left/settings/SettingsPrivacyBlockedUsers.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEnabled.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaPassword.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaStart.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaSkippableForm.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaCongratulations.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEmailCode.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFa.tsx","webpack:///./src/components/common/Picker.tsx","webpack:///./src/components/left/settings/SettingsPrivacyVisibilityExceptionList.tsx","webpack:///./src/components/left/settings/Settings.tsx","webpack:///./src/components/left/main/ContactList.tsx","webpack:///./src/components/left/newChat/NewChatStep1.tsx","webpack:///./src/components/left/newChat/NewChatStep2.tsx","webpack:///./src/components/left/newChat/NewChat.tsx","webpack:///./src/components/left/ArchivedChats.tsx","webpack:///./src/util/scrollLock.ts","webpack:///./src/components/middle/message/helpers/copyOptions.ts","webpack:///./src/components/middle/message/MessageContextMenu.tsx","webpack:///./src/components/middle/message/ContextMenuContainer.tsx","webpack:///./src/components/common/StickerSetModal.tsx","webpack:///./src/components/middle/HeaderMenuContainer.tsx","webpack:///./src/components/middle/MobileSearch.tsx","webpack:///./src/util/isFullyVisible.ts","webpack:///./src/components/middle/composer/MentionMenu.tsx","webpack:///./src/util/findInViewport.ts","webpack:///./src/components/middle/composer/AttachmentModal.tsx","webpack:///./src/components/middle/composer/PollModal.tsx","webpack:///./src/hooks/useMouseInside.ts","webpack:///./src/components/middle/composer/EmojiButton.tsx","webpack:///./src/components/middle/composer/EmojiCategory.tsx","webpack:///./src/components/middle/composer/EmojiPicker.tsx","webpack:///./src/components/middle/composer/StickerSet.tsx","webpack:///./src/components/middle/composer/StickerPicker.tsx","webpack:///./src/components/common/GifButton.tsx","webpack:///./src/components/middle/composer/GifPicker.tsx","webpack:///./src/components/middle/composer/SymbolMenuFooter.tsx","webpack:///./src/components/middle/composer/SymbolMenu.tsx","webpack:///./src/components/middle/composer/AttachMenu.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.tsx","webpack:///./src/components/right/RightSearch.tsx","webpack:///./src/components/right/StickerSetResult.tsx","webpack:///./src/components/right/StickerSearch.tsx","webpack:///./src/components/right/GifSearch.tsx","webpack:///./src/components/right/PollAnswerResults.tsx","webpack:///./src/components/right/PollResults.tsx","webpack:///./src/components/right/management/ManageUser.tsx","webpack:///./src/components/right/management/ManageGroup.tsx","webpack:///./src/components/right/management/ManageGroupPermissions.tsx","webpack:///./src/components/right/management/ManageGroupRemovedUsers.tsx","webpack:///./src/components/right/management/ManageChannel.tsx","webpack:///./src/components/right/management/ManageChatPrivacyType.tsx","webpack:///./src/components/right/management/ManageDiscussion.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissions.tsx","webpack:///./src/components/right/management/ManageChatAdministrators.tsx","webpack:///./src/components/right/management/ManageGroupRecentActions.tsx","webpack:///./src/components/right/management/ManageGroupAdminRights.tsx","webpack:///./src/components/right/management/ManageGroupMembers.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissionsCreate.tsx","webpack:///./src/components/right/management/Management.tsx","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/components/common/helpers/detectCardType.ts","webpack:///./src/hooks/reducers/usePaymentReducer.ts","webpack:///./src/hooks/useFocusAfterAnimation.tsx","webpack:///./src/components/ui/Select.tsx","webpack:///./src/components/payment/ShippingInfo.tsx","webpack:///./src/components/payment/Shipping.tsx","webpack:///./src/components/payment/Checkout.tsx","webpack:///./src/components/payment/ExpiryInput.tsx","webpack:///./src/components/middle/helpers/inputFormatters.ts","webpack:///./src/assets/mastercard.svg","webpack:///./src/assets/visa.svg","webpack:///./src/components/payment/CardInput.tsx","webpack:///./src/components/payment/PaymentInfo.tsx","webpack:///./src/components/payment/PaymentModal.tsx","webpack:///./src/components/payment/ReceiptModal.tsx","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx"],"names":["animateOpening","hasFooter","origin","bestImageData","message","mediaEl","fromImage","getNodes","width","windowWidth","windowSize","get","mediaSize","isVideo","photo","video","webPage","getMessageContent","Boolean","getVideoDimensions","getPhotoFullDimensions","AVATAR_FULL_DIMENSIONS","availableWidth","height","availableHeight","getMediaViewerAvailableDimensions","toWidth","toHeight","calculateDimensions","toLeft","toTop","mql","window","matchMedia","MEDIA_VIEWER_MEDIA_QUERY","topOffsetRem","matches","REM","getTopOffset","top","fromTop","left","fromLeft","fromWidth","fromHeight","getBoundingClientRect","MediaViewerOrigin","SharedMedia","Album","ScheduledAlbum","SearchResult","includes","uncovered","realWidth","realHeight","size","Math","max","srcWidth","srcHeight","uncover","fromTranslateX","fromTranslateY","fromScaleX","fromScaleY","ghost","createGhost","applyStyles","transform","applyShape","document","body","classList","add","requestAnimationFrame","appendChild","style","firstChild","objectFit","remove","clearShape","setTimeout","removeChild","ANIMATION_END_DELAY","animateClosing","container","toImage","getElementById","querySelector","targetTop","el","display","rect","windowHeight","isElementInViewport","shouldFadeOut","Inline","ScheduledInline","isMessageImageFullyVisible","ProfileAvatar","opacity","source","shouldAppendProfileInfo","createElement","img","Image","src","HTMLVideoElement","poster","profileInfo","cloneNode","imageEl","messageListElement","imgOffsetTop","offsetTop","closest","id","parentElement","scrollTop","offsetHeight","element","styles","Object","assign","containerSelector","mediaSelector","MiddleHeaderAvatar","mediaEls","querySelectorAll","length","withGlobal","global","chatId","messageId","isAvatar","sender","isChatPrivate","selectUser","selectChat","selectChatMessage","selectSender","setGlobal","actions","pick","closeMediaViewer","focusMessage","handleFocusMessage","useCallback","useLang","isFromChat","senderTitle","getSenderTitle","className","onClick","Avatar","key","chat","user","renderText","formatMediaDateTime","date","MediaViewerActions","mediaData","isZoomed","fileName","onCloseMediaViewer","onForward","onZoomToggle","isVideoDownloadAllowed","setIsVideoDownloadAllowed","useState","videoMediaHash","getMessageMediaHash","undefined","videoBlobUrl","downloadProgress","useMediaWithDownloadProgress","useEffect","download","handleVideoDownloadClick","e","stopPropagation","isAllowed","lang","MenuButton","useMemo","onTrigger","isOpen","Button","round","color","ariaLabel","IS_MOBILE_SCREEN","DropdownMenu","trigger","positionX","MenuItem","icon","href","ProgressSpinner","progress","noCross","MediaViewerFooter","text","isHideable","isMultiline","setIsMultiline","footerContent","checkIsMultiline","clientHeight","handleResize","throttle","addEventListener","removeEventListener","prop","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","getBrowserFullscreenElementProp","units","bytes","number","floor","log","toFixed","stopEvent","VideoPlayerControls","bufferedProgress","currentTime","duration","fileSize","isForceVisible","isForceMobileVersion","isPlayed","isFullscreenSupported","isFullscreen","onChangeFullscreen","onPlayPause","onSeek","isVisible","setVisibility","timeout","clearTimeout","downloadedPercent","totalSize","percentagePlayed","percentageBuffered","min","step","type","onInput","value","renderSeekLine","ripple","formatMediaDuration","renderTime","formatFileSize","memo","url","isGif","posterData","posterSize","isMediaViewerOpen","noPlay","onClose","videoRef","useRef","setIsPlayed","IS_TOUCH_ENV","IS_IOS","setCurrentTime","isControlsVisible","setIsControlsVisible","setFullscreen","exitFullscreen","elRef","setIsFullscreen","useLayoutEffect","listener","listenerEnter","listenerExit","current","PLATFORM_ENV","requestFullscreen","webkitRequestFullscreen","webkitEnterFullscreen","mozRequestFullScreen","mozCancelFullScreen","webkitCancelFullScreen","webkitExitFullscreen","useFullscreenStatus","isBuffered","bufferingHandlers","useBuffering","shouldRender","shouldRenderSpinner","transitionClassNames","spinnerClassNames","useShowTransition","pause","safePlay","togglePlayState","play","useVideoCleanup","handleMouseOver","handleMouseOut","handleTimeUpdate","currentTarget","handleEnded","handleFullscreenChange","handleSeek","Number","target","toggleControls","togglePayingStateBySpace","wrapperStyle","videoStyle","onMouseOver","onMouseOut","ref","autoPlay","playsInline","loop","muted","onEnded","onTimeUpdate","join","square","isShown","onChangeZoom","prevIsShown","usePrevious","inputRef","zoomLevel","setZoomLevel","isSeeking","handleStartSeek","handleStopSeek","buildClassName","disabled","onChange","onMouseDown","onMouseUp","INITIAL_MATRIX","SCALE_VALUES","1","1.5","2","2.5","3","children","noWrap","canPan","panDeltaX","panDeltaY","onPan","tunedZoomLevel","isDragging","setIsDragging","dragData","setDragData","dx","dy","x","y","matrixData","setMatrixData","panWrapperRef","panContainerRef","newZoomLevel","newPandx","newPandy","newMatrixData","areSortedArraysEqual","oldScale","wrapper","image","wrapperRect","imageRect","newImgWidth","newImgHeight","newImgX","newImgY","calculateSafeZoneOnZoom","toString","preventDefault","newDragData","pageX","pageY","onMouseMove","deltaX","deltaY","getNewMatrixData","renderPhoto","blobUrl","imageSize","alt","draggable","Spinner","threadId","avatarOwnerId","profilePhotoIndex","mediaViewer","animationLevel","settings","byKey","senderId","avatarOwner","chatMessages","collectionIds","selectScheduledMessage","selectScheduledMessages","selectChatMessages","selectOutlyingIds","selectListedIds","currentSearch","selectCurrentMediaSearch","foundIds","resultsByType","media","openMediaViewer","openForwardMenu","animationKey","webPagePhoto","getMessageWebPagePhoto","getMessagePhoto","getMessageVideo","isWebPagePhoto","isPhoto","isFromSharedMedia","isFromSearch","slideAnimation","headerAnimation","isGhostAnimation","getMessageMediaFilename","prevSenderId","canPanZoomWrap","setCanPanZoomWrap","setIsZoomed","panDelta","setPanDelta","messageIds","getChatMediaMessageIds","selectedMediaMessageIndex","indexOf","isFirst","isLast","getMediaHash","full","photos","getChatAvatarHash","blobUrlPictogram","useMedia","ApiMediaFormat","BlobUrl","previewMediaHash","blobUrlPreview","startsWith","DataUri","fullMediaData","getMessageMediaFormat","localBlobUrl","thumbDataUri","useBlurSync","getMessageMediaThumbDataUri","photoDimensions","videoDimensions","toggle","forceUpdate","useForceUpdate","addListener","removeListener","prevMessage","prevOrigin","prevAvatarOwner","prevBestImageData","dispatchHeavyAnimationEvent","textParts","renderMessageText","timer","closeZoom","handleZoomToggle","handleZoomValue","level","canCloseZoom","close","handleFooterClick","handleForward","fromChatId","captureEscKeyListener","stopCurrentAudio","getMessageId","fromId","direction","index","selectPreviousMedia","selectNextMedia","handleKeyDown","shouldCloseOnVideo","captureEvents","excludedClosestSelector","onSwipe","SwipeDirection","Right","Left","handlePan","renderSlide","isActive","calculateMediaViewerDimensions","renderSenderInfo","ShowTransition","Transition","activeKey","name","aria-label","chats","byId","chatsById","listIds","currentUserId","activeListIds","active","archivedListIds","archived","setForwardChatId","exitForwardMode","loadMoreChats","filter","setFilter","focus","blur","chatIds","sortChatIds","getCanPostInChat","MAIN_THREAD_ID","searchWords","getChatTitle","viewportIds","getMore","useInfiniteScroll","handleFilterChange","modalHeader","InputText","placeholder","Modal","header","InfiniteScroll","items","onLoadMore","noScrollRestore","map","ListItem","PrivateChatInfo","status","userId","GroupChatInfo","Loading","getErrorHeader","error","isSlowMode","errors","dismissError","title","getReadableErrorText","isText","notifications","dismissNotification","Notification","onDismiss","WEEKDAY_LETTERS","isDisabledDay","year","month","day","minDate","maxDate","selectedDay","Date","fixedMinDate","getFullYear","getMonth","getDate","fixedMaxDate","formatInputTime","String","padStart","selectedAt","maxAt","isFutureMode","isPastMode","withTimePicker","submitButtonLabel","secondButtonLabel","onSubmit","onSecondButtonClick","now","defaultSelectedDate","selectedDate","setSelectedDate","selectedHours","setSelectedHours","getHours","selectedMinutes","setSelectedMinutes","getMinutes","currentYear","currentMonth","currentDate","shouldDisableNextMonth","shouldDisablePrevMonth","calendarGrid","grid","setFullYear","setMonth","setDate","monthStartDay","getDay","i","push","gridDate","buildCalendarGrid","handleChangeHours","replace","hours","getTime","setHours","hoursStr","handleChangeMinutes","minutes","setMinutes","minutesStr","formatMonthAndYear","d","dateCopy","letter","role","tabIndex","handleDateSelect","inputMode","formatHumanDate","formatTime","formatSubmitLabel","isSchedule","selectCurrentMessageList","canDeleteForAll","selectAllowedMessageActions","contactName","getUserFirstOrLastName","getPrivateChatUserId","willDeleteForCurrentUserOnly","isChatBasicGroup","willDeleteForAll","isChatSuperGroup","album","deleteMessages","deleteScheduledMessages","handleDeleteMessageForAll","messages","shouldDeleteForAll","handleDeleteMessageForSelf","onEnter","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","isChannel","isChatChannel","isGroup","isSuperGroup","canPinForAll","pinMessage","handlePinMessageForAll","isUnpin","handlePinMessage","isOneSide","isSilent","pinnedIds","selectPinnedIds","pinnedMessagesCount","onUnpin","selectedMessageIds","selectedMessages","selectCanDeleteSelectedMessages","selectCurrentChat","exitMessageSelectMode","messageListType","canDelete","selectedMessagesCount","selectSelectedMessagesCount","canDeleteMessages","canPost","openForwardMenuForSelectedMessages","isDeleteModalOpen","openDeleteModal","closeDeleteModal","useFlag","captureKeyboardListeners","onBackspace","onDelete","onEsc","prevSelectedMessagesCount","renderingSelectedMessagesCount","formattedMessagesCount","destructive","privateChatUserId","privateChatUser","isPinned","selectIsChatPinned","withUsername","contextActions","useChatContextActions","handleDelete","avatarSize","DeleteChatModal","runThrottled","cb","userIds","topUserIds","topPeers","usersById","users","recentlyFoundChatIds","globalSearch","onReset","loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats","topUsersRef","useHorizontalScroll","handleClick","lastSyncTime","searchQuery","mediaThumbnail","mediaBlobUrl","withOnlineStatus","isSavedMessages","isSelf","isVerified","VerifiedIcon","Link","formatPastTimeShort","getMessageSummaryText","highlight","renderMessageSummary","searchDate","onSelect","suggestions","match","formatDateToString","suggestion","latestYear","getSuggestionsFromDate","localContactIds","contactList","fetchingStatus","globalResults","localResults","globalChatIds","globalUserIds","localChatIds","localUserIds","byChatId","globalMessagesByChatId","dateSearchQuery","onSearchDateSelect","searchMessagesGlobal","setGlobalSearchChatId","shouldShowMoreLocal","setShouldShowMoreLocal","shouldShowMoreGlobal","setShouldShowMoreGlobal","handleLoadMore","LoadMoreDirection","Backwards","query","handleChatClick","handlePickerItemClick","MEMO_EMPTY_ARRAY","foundContactIds","fullName","getUserFullName","username","getTranslation","unique","foundMessages","split","sort","a","b","handleClickShowMoreLocal","handleClickShowMoreGlobal","nothingFound","noFastList","NothingFound","PickerSelectedItem","chatOrUserId","clickArg","createMapStateToProps","props","currentType","isVoice","isLoading","searchChatId","handleSelectMedia","canRenderContents","useAsyncRendering","SLIDE_TRANSITION_DURATION","isMediaGrid","isMessageList","classNames","itemSelector","Media","idPrefix","getSenderName","senderName","isChatGroup","handleMessageFocus","shouldDrawDateDivider","toYearMonth","WebLink","onMessageClick","getMessageDocument","Document","withDate","datetime","smaller","onDateClick","openAudioPlayer","handlePlayAudio","Audio","renderingFor","onPlay","TABS","GlobalSearchContent","ChatList","Links","Files","Music","Voice","CHAT_TABS","slice","TRANSITION_RENDER_COUNT","keys","currentContent","setGlobalSearchContent","setGlobalSearchDate","activeTab","setActiveTab","parseDateString","handleSwitchTab","tab","content","handleSearchDateSelect","TabList","tabs","onSwitchTab","renderCount","useReducer","reducer","initialState","reducerRef","state","setState","action","currentState","INCLUDED_CHAT_TYPES","EXCLUDED_CHAT_TYPES","INCLUDE_FILTER_FIELDS","EXCLUDE_FILTER_FIELDS","selectChatFilters","mode","selectTemp","selectedChatIds","selectedChatTypes","includedChatIds","includeFilters","folder","excludedChatIds","excludeFilters","getSuggestedFolderName","filters","values","bots","groups","channels","contacts","nonContacts","INITIAL_STATE","chatFilter","foldersReducer","payload","isTouched","omit","folderId","description","currentPassword","password","hint","email","twoFaReducer","currentScreen","editedFolderId","onSaveFilter","signOut","deleteChatFolder","isSignOutDialogOpen","setIsSignOutDialogOpen","isDeleteFolderDialogOpen","setIsDeleteFolderDialogOpen","openSignOutConfirmation","closeSignOutConfirmation","openDeleteFolderConfirmation","closeDeleteFolderConfirmation","handleSignOutMessage","handleDeleteFolderMessage","SettingsMenuButton","SettingsScreens","EditProfile","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyPhoneNumberAllowedContacts","PrivacyLastSeenAllowedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyForwardingAllowedContacts","PrivacyGroupChatsAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsDeniedContacts","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaNewPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaChangePasswordHint","TwoFaNewPasswordEmail","TwoFaRecoveryEmail","TwoFaNewPasswordEmailCode","TwoFaRecoveryEmailCode","TwoFaCongratulations","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","Folders","FoldersCreateFolder","FoldersEditFolder","FoldersIncludedChats","FoldersExcludedChats","renderHeaderContent","ConfirmDialog","confirmLabel","confirmHandler","confirmIsDestructive","currentUser","onScreenSelect","formatPhoneNumberWithCode","phoneNumber","FloatingActionButton","buttonClassName","LINK_PREFIX_REGEX","USERNAME_REGEX","runDebouncedForCheckUsername","debounce","currentUsername","asLink","isUsernameAvailable","checkUsername","setUsername","langPrefix","label","usernameSuccess","usernameError","test","handleUsernameChange","newUsername","trim","isValid","isUsernameValid","success","readOnly","profileEdit","firstName","currentFirstName","lastName","currentLastName","fullInfo","bio","currentBio","currentAvatarHash","loadCurrentUser","updateProfile","isUsernameTouched","setIsUsernameTouched","isProfileFieldsTouched","setIsProfileFieldsTouched","setError","setPhoto","setFirstName","setLastName","setBio","currentAvatarBlobUrl","ProfileEditProgress","InProgress","isUsernameError","isSaveButtonShown","Complete","handlePhotoChange","newPhoto","handleFirstNameChange","handleLastNameChange","handleBioChange","handleProfileSave","trimmedFirstName","trimmedLastName","trimmedBio","AvatarEditable","UsernameInput","runThrottledForLoadRecommended","orderedIds","orderedFolderIds","foldersById","recommended","recommendedChatFolders","chatFolders","onCreateFolder","onEditFolder","loadRecommendedChatFolders","addChatFolder","showError","animationData","setAnimationData","isAnimationLoaded","setIsAnimationLoaded","handleAnimationLoad","getAnimationData","then","handleCreateFolder","userFolders","subtitle","getFolderDescriptionText","handleCreateFolderFromRecommended","AnimatedSticker","STICKER_SIZE_FOLDER_SETTINGS","noLoop","onLoad","pill","fluid","narrow","multiline","ShowMoreButton","count","itemName","itemPluralName","ERROR_NO_TITLE","ERROR_NO_CHATS","loadedActiveChatIds","loadedArchivedChatIds","dispatch","onAddIncludedChats","onAddExcludedChats","editChatFolder","isIncludedChatsListExpanded","setIsIncludedChatsListExpanded","isExcludedChatsListExpanded","setIsExcludedChatsListExpanded","includedChatTypes","excludedChatTypes","visibleIncludedChatIds","visibleExcludedChatIds","allLoadedChatsSet","Set","loadedIncludedChatIds","findIntersectionWithSet","loadedExcludedChatIds","listType","renderChats","visibleChatIds","isExpanded","leftChatsCount","clickHandler","chatType","find","typeKey","inactive","renderChatType","event","folderUpdate","selectedIds","filterValue","onSelectedIdsChange","onSelectedChatTypesChange","onFilterChange","chatTypes","shouldMinimize","hasMaxChats","handleItemClick","newSelectedIds","splice","handleChatTypeClick","newSelectedChatTypes","selectedType","isMinimized","canClose","Checkbox","checked","isSelected","withChatType","orderedPinnedIds","archivedPinnedIds","activeChatArrays","prepareChatList","archivedChatArrays","pinnedChats","otherChats","displayedIds","newFilter","handleSelectedIdsChange","ids","handleSelectedChatTypesChange","newFilters","forEach","handleReset","handleEditFolder","handleAddIncludedChats","handleAddExcludedChats","options","range","handleChange","trackWidth","possibleValuesLength","option","STICKER_SIZE_PICKER_HEADER","stickerSet","observeIntersection","isIntersecting","useIsIntersecting","mediaHash","lottieData","Lottie","shouldRenderFullMedia","useTransitionForMedia","getFirstLetters","hasThumbnail","sticker","noAnimate","onUnfaveClick","isAnimated","localMediaHash","stickerSelector","thumbnail","dataUri","previewBlobUrl","shouldPlay","markLoaded","unmarkLoaded","canAnimatedPlay","shouldRenderThumb","shouldRenderPreview","previewTransitionClassNames","fullClassName","emoji","data-sticker-id","isLowPriority","stickers","firstSticker","STICKER_SIZE_GENERAL_SETTINGS","KEYBOARD_SEND_OPTIONS","subLabel","IS_MAC_OS","ANIMATION_LEVEL_OPTIONS","stickerSetIds","added","setIds","stickerSetsById","setsById","messageTextSize","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers","setSettingOption","loadStickerSets","loadAddedStickers","stickerSettingsRef","observe","observeIntersectionForCovers","useIntersectionObserver","rootRef","isModalOpen","openModal","closeModal","setSticker","handleAnimationLevelChange","newLevel","_","handleMessageTextSizeChange","newSize","documentElement","setProperty","handleStickerSetClick","stickerSets","installedDate","RadioGroup","selected","onCheck","isChecked","fromSticker","fileSelector","openSystemFilesDialog","accept","callback","noMultiple","setAttribute","removeAttribute","onchange","click","hex2rgb","param","parseInt","substring","rgb2hex","p0","p1","p2","rgb2hsb","r","g","h","s","v","hsb2rgb","f","p","q","t","getPatternColor","rgbColor","hue","saturation","wallpaper","slug","useBlur","isDownloadAllowed","setIsDownloadAllowed","fullMedia","wasDownloadDisabled","UPLOADING_WALLPAPER_SLUG","handleSelect","blob","fetchBlob","cacheApi","CUSTOM_BG_CACHE_NAME","isBackgroundBlurred","customBackground","loadedWallpapers","loadWallpapers","uploadWallpaper","handleFileSelect","files","handleUploadWallpaper","handleSetColor","handleResetToDefault","patternColor","DEFAULT_PATTERN_COLOR","handleWallPaperSelect","currentWallpaper","async","defaultRGB","data","rgb","canvas","context","getContext","preloadImage","naturalHeight","naturalWidth","offsetWidth","drawImage","getImageData","blockSize","getAverageColor","handleWallPaperBlurChange","isUploading","DEFAULT_HSB","PREDEFINED_COLORS","hsb2positions","hsb","rects","colorPosition","colorRect","huePosition","hueRect","positions2hsb","containerRef","colorPickerRef","huePickerRef","isFirstRunRef","setHsb","getInitialHsb","hsbRef","markIsDragging","unmarkIsDragging","rgbInput","setRgbInput","hexInput","setHexInput","rectsRef","colorCtxRef","offsetLeft","handleColorDrag","handleHueDrag","onCapture","onDrag","onRelease","withCursor","hex","hueHex","w","ctx","imgData","createImageData","pixels","col","perY","st","ed","perX","putImageData","drawColor","drawHue","handleRgbChange","rgbValue","channel","handleHexChange","hexValue","handlePredefinedColorClick","dataset","data-color","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","hasContactJoinedNotifications","loadNotificationsSettings","updateContactSignUpNotification","updateNotificationSettings","handleSettingsChange","peerType","setting","currentIsSilent","currentIsShowPreviews","isShowPreviews","handleContactNotificationChange","hasPassword","privacy","blocked","activeSessions","blockedCount","totalCount","sessionsCount","visibilityPrivacyPhoneNumber","visibility","visibilityPrivacyLastSeen","lastSeen","visibilityPrivacyProfilePhoto","profilePhoto","visibilityPrivacyForwarding","forwards","visibilityPrivacyGroupChats","chatInvite","loadPrivacySettings","loadBlockedContacts","loadAuthorizations","getVisibilityValue","languages","language","loadLanguages","selectedLanguage","setSelectedLanguage","markIsLoading","unmarkIsLoading","langCode","setLanguage","nativeName","buildOptions","loadingOption","getPrivacyKey","screen","privacySettings","allowUserIds","allowChatIds","blockUserIds","blockChatIds","setPrivacyVisibility","visibilityOptions","exceptionLists","shouldShowDenied","shouldShowAllowed","privacyKey","headerText","descriptionText","allowedContactsScreen","deniedContactsScreen","allowedCount","reduce","result","membersCount","blockCount","handleVisibilityChange","getLocation","session","region","country","getDeviceEnvironment","deviceModel","platform","systemVersion","terminateAuthorization","terminateAllAuthorizations","isConfirmTerminateAllDialogOpen","openConfirmTerminateAllDialog","closeConfirmTerminateAllDialog","handleTerminateSessionClick","hash","handleTerminateAllSessions","currentSession","isCurrent","otherSessions","renderSession","handler","dateActive","appName","ip","sessions","chatsByIds","usersByIds","blockedIds","unblockContact","handleUnblockClick","contactId","viewportOffset","isPrivate","CHAT_HEIGHT_PX","renderContact","animatedEmoji","selectAnimatedEmoji","AnimatedEmoji","expectedPassword","submitLabel","clearError","validationError","setValidationError","shouldShowPassword","setShouldShowPassword","handleSubmit","newPassword","handleClearError","PasswordMonkey","isBig","isPasswordVisible","PasswordForm","onChangePasswordVisibility","onStart","FOCUS_DELAY_TIMEOUT_MS","shouldConfirm","setValue","isConfirmShown","markIsConfirmShown","unmarkIsConfirmShown","codeLength","twoFaSettings","waitingEmailCodeLength","newValue","updatePassword","checkPassword","clearTwoFaError","updateRecoveryEmail","provideTwoFaEmailCode","clearPassword","handleStartWizard","handleNewPassword","handleNewPasswordConfirm","handleNewPasswordHint","handleNewPasswordEmail","onSuccess","handleChangePasswordCurrent","handleChangePasswordNew","handleChangePasswordConfirm","handleChangePasswordHint","handleTurnOff","handleRecoveryEmailCurrentPassword","handleRecoveryEmail","handleEmailCode","code","itemIds","filterPlaceholder","notFoundText","searchInputId","getCurrentPrivacySettings","isAllowList","setPrivacySettings","selectedContactIds","setSearchQuery","isSubmitShown","setIsSubmitShown","newSelectedContactIds","setNewSelectedContactIds","handleSelectedContactIdsChange","contactsIds","foldersState","foldersDispatch","twoFaState","twoFaDispatch","handleSaveFilter","renderCurrentSection","Main","renderCurrentSectionContent","contactIds","resultIds","sortUserIds","forceShowSelf","isSearching","selectedMemberIds","onSelectedMemberIdsChange","onNextStep","setGlobalSearchQuery","handleNextStep","creationProgress","creationError","chatCreation","memberIds","createGroupChat","createChannel","setTitle","about","setAbout","ChatCreationProgress","handleTitleChange","handleDescriptionChange","handleCreateGroup","handleCreateChannel","renderedError","RENDER_COUNT","LeftColumnContent","onContentChange","newChatMemberIds","setNewChatMemberIds","NewChannelStep2","NewGroupStep2","NewChannelStep1","NewGroupStep1","folderType","noChatsText","IGNORED_KEYS","Down","ArrowDown","Up","ArrowUp","ArrowLeft","ArrowRight","PageUp","PageDown","End","Home","Tab","preventDefaultForScrollKeys","disableScrolling","passive","ontouchmove","onkeydown","enableScrolling","getCopyLabel","hasSelection","canImageBeCopied","MessageContextMenu","anchor","canSendNow","canReschedule","canReply","canEdit","canPin","canUnpin","canForward","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","onReply","onEdit","onPin","onFaveSticker","onUnfaveSticker","onSend","onReschedule","onCloseAnimationEnd","onCopyLink","copyOptions","afterEffect","getMessageText","CLIPBOARD_ITEM_SUPPORTED","selection","getSelection","mediaLoader","copyImageToClipboard","anchorNode","parentNode","clipboardText","copyTextToClipboard","getMessageCopyOptions","getTriggerElement","getRootElement","getMenuElement","positionY","useContextMenuPosition","Menu","noOptions","isScheduled","setReplyingToId","setEditingId","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink","isMenuOpen","setIsMenuOpen","setIsDeleteModalOpen","isPinModalOpen","setIsPinModalOpen","isCalendarOpen","openCalendar","closeCalendar","closeMenu","closePinModal","handleCloseCalendar","handleReply","handleEdit","handlePin","handleUnpin","handleFaveSticker","handleUnfaveSticker","handleSelectMessage","params","childMessageIds","withShift","handleScheduledMessageSend","handleOpenCalendar","handleRescheduleMessage","scheduledAt","handleCopyLink","scheduledMaxDate","getDayStartAt","selectStickerSet","stickerSetId","loadStickers","toggleStickerSet","sendMessage","throttleMs","isDisabled","stickerSetAccessHash","isPreloadedGlobally","handleButtonClick","hasCloseButton","STICKER_SIZE_MODAL","isRestricted","isMuted","canDeleteChat","getCanDeleteChat","canSubscribe","canSearch","canMute","canLeave","onSubscribeChannel","onSearchClick","updateChatMutedState","enterMessageSelectMode","handleToggleMuteClick","handleSubscribe","handleSearch","handleSelectMessages","Portal","runDebouncedForSearch","results","selectCurrentTextSearch","setLocalTextSearchQuery","searchTextMessagesLocal","closeLocalTextSearch","searchMessagesByDate","focusedIndex","setFocusedIndex","visualViewport","mainEl","activeElement","pageTop","Array","from","input","div","contentEditable","handleMessageSearchQueryChange","newQuery","handleJumpToDate","timestamp","valueOf","handleUp","newFocusIndex","handleDown","SearchInput","isFullyVisible","viewportY1","viewportY2","y1","y2","onInsertUserName","filteredChatMembers","getSelectedIndex","newIndex","cycleRestrict","selectedMentionIndex","setSelectedMentionIndex","handleArrowKey","handleUserSelect","forceFocus","handleSelectMention","member","onUp","onDown","onTab","visibleIndexes","allElements","selectorOrElements","margin","isDense","shouldContainBottom","isFound","findInViewport","first","position","fastSmoothScroll","setItemVisible","prevChatMembers","renderedChatMembers","attachments","caption","canSuggestMembers","groupChatMembers","onCaptionUpdate","onClear","prevAttachments","renderingAttachments","isMentionMenuOpen","mentionFilter","closeMentionMenu","insertMention","mentionFilteredMembers","useMentionMenu","EDITABLE_INPUT_MODAL_ID","sendAttachments","areAllPhotos","every","mimeType","areAllVideos","isQuick","quick","renderHeader","attachment","File","filename","extension","getFileExtension","previewData","MessageInput","html","editableInputId","onUpdate","shouldSetFocus","questionInputRef","optionsListRef","solutionRef","question","setQuestion","setOptions","isAnonymous","setIsAnonymous","isMultipleAnswers","setIsMultipleAnswers","isQuizMode","setIsQuizMode","solution","setSolution","correctOption","setCorrectOption","hasErrors","setHasErrors","focusInput","solutionEl","innerHTML","addNewOption","newOptions","list","scrollHeight","scrollTo","behavior","handleCreate","questionTrimmed","optionsTrimmed","o","summary","answers","correct","isPublic","multipleChoice","quiz","entities","parseMessageInput","correctAnswers","solutionEntities","updateOption","removeOption","handleCorrectOptionChange","handleIsAnonymousChange","handleMultipleAnswersChange","handleQuizModeChange","handleKeyPress","keyCode","getQuestionError","getOptionsError","renderOptions","onKeyPress","renderQuizNoOptionError","hidden","closeTimeout","useMouseInside","menuCloseTimeout","isMouseInside","native","colons","IS_EMOJI_SUPPORTED","loading","category","allEmojis","onEmojiSelect","useOnIntersect","emojisPerRow","ceil","emojis","displayedEmoji","ICONS_BY_CATEGORY","recent","people","nature","foods","activity","places","objects","symbols","flags","categoryIntersections","emojiDataPromise","emojiRawData","emojiData","recentEmojis","addRecentEmoji","headerRef","categories","setCategories","setEmojis","activeCategoryIndex","setActiveCategoryIndex","entries","entry","intersectingWithIndexes","newLeft","HEADER_BUTTON_WIDTH","fastSmoothScrollHorizontal","allCategories","themeCategories","unshift","exec","default","uncompressEmoji","ensureEmojiData","selectCategory","categoryEl","handleEmojiSelect","MENU_TRANSITION_DURATION","containerClassName","faded","STICKER_MARGIN","loadAndPlay","onStickerSelect","onStickerUnfave","stickersPerRow","STICKER_SIZE_PICKER","stickerSetIntersections","favorite","recentStickers","favoriteStickers","addedSetIds","canSendStickers","loadRecentStickers","loadFavoriteStickers","addRecentSticker","activeSetIndex","setActiveSetIndex","areAddedLoaded","allSets","noPopulatedSets","set","stickerSetEl","handleStickerSelect","handleStickerUnfave","gif","videoData","shouldRenderVideo","preload","savedGifs","gifs","saved","canSendGifs","onGifSelect","loadSavedGifs","debounceMs","SymbolMenuTabs","SYMBOL_MENU_TAB_TITLES","SYMBOL_MENU_TAB_ICONS","Emoji","Stickers","GIFs","onRemoveSymbol","onSearchOpen","renderTabButton","handleSearchOpen","isActivated","allowedAttachmentOptions","handleMouseEnter","handleMouseLeave","fastRaf","renderContent","isFrom","onMouseEnter","onMouseLeave","noCloseOnBackdrop","onFileSelect","onPollCreate","handleQuickSelect","CONTENT_TYPES_FOR_QUICK_UPLOAD","handleDocumentSelect","canAttachMedia","canAttachPolls","autoClose","forEmoji","clearStickersForEmoji","prevStickers","displayedStickers","clickInlineButton","keyboardButtons","row","button","onSilentSend","onScheduleSend","messagesById","foundResults","senderUser","getGlobal","senderChat","forwardInfo","isChannelPost","orderBy","preloadBackwards","LastMessageMeta","selectShouldLoopStickers","isSomeModalOpen","onModalToggle","isAdded","areStickersLoaded","useOnChange","coverStickerIds","covers","otherStickers","handleAddClick","canRenderStickers","STICKER_SIZE_SEARCH","selectCurrentStickerSearch","featured","featuredIds","loadFeaturedStickers","setIsModalOpen","selectCurrentGifSearch","isChatWithBot","selectIsChatWithBot","searchMoreGifs","setGifSearchQuery","getAllowedAttachmentOptions","handleGifClick","hasResults","answer","voters","offsets","pollResults","offset","answerVote","totalVoters","loadPollOptionResults","closePollResults","prevVotersCount","votersCount","setIsLoading","areVotersLoaded","limit","shouldResetVoters","handleViewMoreClick","handleMemberClick","noStatusOrTyping","leftVotersCount","renderViewMoreButton","total","getMessagePoll","resultsByOption","buildCollectionByKey","management","updateContact","deleteUser","deleteHistory","closeManagement","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","currentIsMuted","isNotificationsEnabled","setIsNotificationsEnabled","ManagementProgress","handleNotificationChange","handleDeleteContact","lastMessage","maxId","withFullInfo","hasLinkedChannel","linkedChatId","isBasicGroup","canChangeInfo","getHasAdminRight","canBanUsers","togglePreHistoryHidden","updateChat","leaveChannel","deleteChannel","currentTitle","currentAbout","imageHash","handleClickEditType","ManagementScreens","ChatPrivacyType","handleClickDiscussion","Discussion","handleClickPermissions","GroupPermissions","handleClickAdministrators","ChatAdministrators","handleSetPhoto","file","handleAboutChange","handleUpdateGroup","trimmedTitle","trimmedAbout","handleClickMembers","GroupMembers","handleTogglePreHistory","isPreHistoryHidden","isEnabled","enabledPermissionsCount","defaultBannedRights","sendStickers","sendGifs","adminsCount","adminMembers","handleDeleteGroup","isCreator","formatInteger","onChatMemberSelect","updateChatDefaultBannedRights","permissions","setPermissions","havePermissionChanged","setHavePermissionChanged","handleRemovedUsersClick","GroupRemovedUsers","handleAddExceptionClick","GroupUserPermissionsCreate","handleExceptionMemberClick","promotedByUserId","GroupUserPermissions","handlePermissionChange","getUpdatedPermissionValue","handleSavePermissions","bannedRights","removedUsersCount","kickedMembers","exceptionMembers","members","getMemberExceptions","langKey","getLangKeyForBannedRightKey","translatedString","sendMessages","blocking","sendMedia","sendPolls","embedLinks","inviteUsers","pinMessages","changeInfo","updateChatMemberBannedRights","removedMembers","getRemovedBy","kickedByUserId","kickedByUser","getContextActions","isSignaturesShown","toggleSignatures","hasLinkedChat","handleUpdateChannel","handleToggleSignatures","handleClickSubscribers","ChannelSubscribers","handleDeleteChannel","selectManagement","checkPublicLink","updatePublicLink","updatePrivateLink","privateLink","inviteLink","privacyType","setPrivacyType","isRevokeConfirmDialogOpen","openRevokeConfirmDialog","closeRevokeConfirmDialog","canUpdate","handleOptionChange","handleSave","handleRevokePrivateLink","langPrefix1","langPrefix2","SafeLink","forDiscussionIds","linkedChat","loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup","linkedGroupId","setLinkedGroupId","isConfirmUnlinkGroupDialogOpen","openConfirmUnlinkGroupDialog","closeConfirmUnlinkGroupDialog","isConfirmLinkGroupDialogOpen","openConfirmLinkGroupDialog","closeConfirmLinkGroupDialog","handleUnlinkGroupSessions","channelId","Initial","handleLinkGroupSessions","renderLinkGroupHeader","linkedGroup","renderLinkGroupConfirmText","hasPrivateLink","STICKER_SIZE_DISCUSSION_GROUPS","teactFastList","teactOrderKey","isButtonsInOneRow","isPromotedByCurrentUser","isFormFullyDisabled","selectedChatMemberId","isBanConfirmationDialogOpen","openBanConfirmationDialog","closeBanConfirmationDialog","selectedChatMember","handleBanFromGroup","viewMessages","getControlIsDisabled","isOwner","handleAdminMemberClick","ChatAdminRights","getMemberStatus","promotedByUser","GroupRecentActions","updateChatAdmin","setIsTouched","isDismissConfirmationDialogOpen","openDismissConfirmationDialog","closeDismissConfirmationDialog","customTitle","setCustomTitle","adminRights","substr","handleDismissAdmin","memberStatus","handleCustomTitleChange","postMessages","editMessages","banUsers","addAdmins","anonymous","maxLength","openUserInfo","memberId","managementType","selectCurrentManagementType","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","VISA","MASTERCARD1","MASTERCARD2","CardType","cards","Default","Visa","Mastercard","detectCardType","cardNumber","streetLine1","streetLine2","city","countryIso2","postCode","phone","shipping","cardholder","expiry","cvv","billingCountry","billingZip","saveInfo","saveCredentials","formErrors","getBillingCountry","countryCode","countryList","useFocusAfterAnimation","animationDuration","hasArrow","labelText","htmlFor","needEmail","needPhone","needName","needAddress","phoneRef","selectCountryRef","handleAddress1Change","handleAddress2Change","handleCityChange","handleStateChange","handleCountryChange","handlePostCodeChange","handleFullNameChange","handleEmailChange","handlePhoneChange","handleSaveInfoChange","shippingOptions","handleShippingSelect","amount","renderPaymentItem","main","renderCheckoutItem","invoiceContent","prices","shippingPrices","checkoutInfo","totalPrice","photoUrl","paymentMethod","paymentProvider","shippingAddress","shippingMethod","item","expiryInputRef","charAt","parts","formatCardExpiry","onKeyDown","cardNumberRef","cardType","setCardType","newCardType","formatCardNumber","cardIcon","mastercardIconPath","visaIconPath","getCardIcon","canSaveCredentials","needCardholderName","needCountry","needZip","handleCardNumberChange","handleCardholderChange","toUpperCase","handleExpiryChange","handleCvvChange","handleBillingPostCodeChange","handleChangeSaveCredentials","savedInfo","invoice","nativeProvider","nativeParams","passwordMissing","payment","isProviderError","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","globalErrors","validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError","paymentState","paymentDispatch","currencySign","field","fieldError","getShippingError","handleErrorModalClose","PaymentStep","Checkout","shippingOption","getShippingPrices","totalPrices","concat","acc","cur","getTotalPrice","detectCardTypeText","findShippingOption","getCheckoutInfo","validateRequest","requestInfo","getRequestInfo","sendCredentials","credentials","expiryMonth","expiryYear","zip","getCredentials","sendForm","shippingOptionId","setStep","nextStep","ShippingInfo","Shipping","PaymentInfo","buttonText","cuurentStep","renderModalContent","renderError","optionId","receipt","mapedPrices","info","totalAmount","credentialsTitle","fullAddress","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","path","location","cropperResultOptions","quality","format","circle","Croppie","croppiePromise","cropper","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","enableZoom","boundary","viewport","blobToDataUri","bind","err","DEBUG","console","initCropper","ensureCroppie","croppedImg","blobToFile","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","URL","revokeObjectURL","createObjectURL","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","playSegment","onInputChange","setPassword","canSubmit","setCanSubmit","select","autoComplete","MIN_PASSWORD_LENGTH"],"mappings":"s9DAiBO,SAASA,EACdC,EAAoBC,EAA2BC,EAAuBC,GAEtE,MAAQC,QAASC,GAAcC,EAASL,EAAQE,GAChD,IAAKE,EACH,OAGF,MAAQE,MAAOC,GAAgBC,IAAWC,MAE1C,IACIC,EADAC,GAAU,EAEd,GAAIT,EAAS,CACX,MAAM,MAAEU,EAAF,MAASC,EAAT,QAAgBC,GAAYC,YAAkBb,GACpDS,EAAUK,QAAQH,GAClBH,EAAYG,EAAQI,aAAmBJ,GAAUK,YAAwBN,GAASE,EAASF,YAE3FF,EAAYS,IAId,MACEb,MAAOc,EAAgBC,OAAQC,GAC7BC,YAAkCxB,EAAWY,IACzCL,MAAOkB,EAASH,OAAQI,GAAaC,YAC3CN,EAAgBE,EAAiBZ,EAAUJ,MAAOI,EAAUW,QAExDM,GAAUpB,EAAciB,GAAW,EACnCI,EA+MR,SAAsB7B,GACpB,MAAM8B,EAAMC,OAAOC,WAAWC,KAC9B,IAAIC,EAAe,MACflC,IACFkC,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Aa72C,EAAO2B,QACpB+1C,WAAY,IACP53C,EAAM43C,WACTb,iBAAahiE,IAGnB,IAAK,aACH,MAAO,IACFirB,EACHg3C,KAAM92C,EAAO2B,QACb+1C,WAAY,IACP53C,EAAM43C,WACTZ,UAAMjiE,IAGZ,IAAK,cACH,MAAO,IACFirB,EACHA,MAAOE,EAAO2B,QACd+1C,WAAY,IACP53C,EAAM43C,WACT53C,WAAOjrB,IAGb,IAAK,gBACH,MAAO,IACFirB,EACHi3C,YAAa/2C,EAAO2B,QACpB21C,eAAgBK,GAAkB33C,EAAO2B,SACzC+1C,WAAY,IACP53C,EAAM43C,WACTX,iBAAaliE,IAGnB,IAAK,iBACH,MAAO,IACFirB,EACHk3C,SAAUh3C,EAAO2B,QACjB+1C,WAAY,IACP53C,EAAM43C,WACTV,cAAUniE,IAGhB,IAAK,iBACH,MAAO,IACFirB,EACHlF,SAAUoF,EAAO2B,QACjB+1C,WAAY,IACP53C,EAAM43C,WACT98C,cAAU/lB,IAGhB,IAAK,cACH,MAAO,IACFirB,EACHqC,MAAOnC,EAAO2B,QACd+1C,WAAY,IACP53C,EAAM43C,WACTv1C,WAAOttB,IAGb,IAAK,cACH,MAAO,IACFirB,EACHm3C,MAAOj3C,EAAO2B,QACd+1C,WAAY,IACP53C,EAAM43C,WACTT,WAAOpiE,IAGb,IAAK,iBACH,MAAO,IAAKirB,EAAOo3C,SAAUl3C,EAAO2B,SACtC,IAAK,mBACH,MAAO,IACF7B,EACH62C,WAAY32C,EAAO2B,QACnB+1C,WAAY,IACP53C,EAAM43C,WACTf,gBAAY9hE,IAGlB,IAAK,mBACH,MAAO,IACFirB,EACHq3C,WAAYn3C,EAAO2B,QACnB+1C,WAAY,IACP53C,EAAM43C,WACTP,gBAAYtiE,IAGlB,IAAK,mBACH,MAAO,IACFirB,EACHs3C,OAAQp3C,EAAO2B,QACf+1C,WAAY,IACP53C,EAAM43C,WACTN,YAAQviE,IAGd,IAAK,gBACH,MAAO,IACFirB,EACHu3C,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ooE,YAGrB,CAAC/2D,IAgCF,0BAAMkT,OAAO,GAAG/Q,SAblB,SAAsB2f,GACpBA,EAAM3sB,iBAEFia,GAIAynD,GACF10D,EAASgT,IAK6B6hD,aAAa,OACnD,yBAAKtwE,UAAW0L,YAAe,6BAA8B+iB,GAAY,UAAWnV,GAAS,UAC3F,2BACE/O,IAAKa,EACLpL,UAAU,eACViG,KAAMgtC,EAAoB,OAAS,WACnCr1C,GAAG,mBACHuI,MAAOsoB,GAAY,GACnB6hD,aAAa,mBACb1kE,SAvCR,SAA0BhK,GACpB0X,GACFi5B,IAGF,MAAM,OAAEvoC,GAAWpI,EACnBsuE,EAAYlmE,EAAO7D,OACnBiqE,EAAapmE,EAAO7D,MAAM1H,QAAU8xE,KAChCN,GACFA,EAAcjmE,EAAO7D,UAgCnB,+BAAQmT,GAASoV,GAAQnW,GACzB,yBACEvY,UAAU,kBACVC,QA/BR,WACEkzC,GAA4BF,IA+BtB90B,KAAK,SACLC,SAAU,EACV1E,MAAM,8BAEN,uBAAG1Z,UAAWizC,EAAoB,WAAa,sBAGlDk9B,GACC,kBAAC,IAAD,CAAQlqE,KAAK,SAASI,QAAM,EAACqiB,UAAWA,GACrC4pB,O","file":"2.07f32bea8faa762b432b.js","sourcesContent":["import { ApiMessage } from '../../../api/types';\nimport { MediaViewerOrigin } from '../../../types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { getMessageContent, getPhotoFullDimensions, getVideoDimensions } from '../../../modules/helpers';\nimport {\n AVATAR_FULL_DIMENSIONS,\n calculateDimensions,\n getMediaViewerAvailableDimensions,\n MEDIA_VIEWER_MEDIA_QUERY,\n REM,\n} from '../../common/helpers/mediaDimensions';\n\nimport windowSize from '../../../util/windowSize';\n\nconst ANIMATION_DURATION = 200;\n\nexport function animateOpening(\n hasFooter: boolean, origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage,\n) {\n const { mediaEl: fromImage } = getNodes(origin, message);\n if (!fromImage) {\n return;\n }\n\n const { width: windowWidth } = windowSize.get();\n\n let isVideo = false;\n let mediaSize;\n if (message) {\n const { photo, video, webPage } = getMessageContent(message);\n isVideo = Boolean(video);\n mediaSize = video ? getVideoDimensions(video)! : getPhotoFullDimensions((photo || webPage!.photo)!)!;\n } else {\n mediaSize = AVATAR_FULL_DIMENSIONS;\n }\n\n // eslint-disable-next-line max-len\n const {\n width: availableWidth, height: availableHeight,\n } = getMediaViewerAvailableDimensions(hasFooter, isVideo);\n const { width: toWidth, height: toHeight } = calculateDimensions(\n availableWidth, availableHeight, mediaSize.width, mediaSize.height,\n );\n const toLeft = (windowWidth - toWidth) / 2;\n const toTop = getTopOffset(hasFooter) + (availableHeight - toHeight) / 2;\n\n let {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n const uncovered = uncover(toWidth, toHeight, fromTop, fromLeft, fromWidth, fromHeight);\n fromTop = uncovered.top;\n fromLeft = uncovered.left;\n fromWidth = uncovered.width;\n fromHeight = uncovered.height;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n const fromScaleX = fromWidth / toWidth;\n const fromScaleY = fromHeight / toHeight;\n\n const ghost = createGhost(bestImageData || fromImage);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n applyShape(ghost, origin);\n\n document.body.classList.add('ghost-animating');\n\n requestAnimationFrame(() => {\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n clearShape(ghost);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n document.body.removeChild(ghost);\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nexport function animateClosing(origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage) {\n const { container, mediaEl: toImage } = getNodes(origin, message);\n if (!toImage) {\n return;\n }\n\n const fromImage = document.getElementById('MediaViewer')!.querySelector(\n '.active .media-viewer-content img, .active .media-viewer-content video',\n );\n if (!fromImage || !toImage) {\n return;\n }\n\n const {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n const {\n top: targetTop, left: toLeft, width: toWidth, height: toHeight,\n } = toImage.getBoundingClientRect();\n\n let toTop = targetTop;\n if (!isElementInViewport(container)) {\n const { height: windowHeight } = windowSize.get();\n toTop = targetTop < fromTop ? -toHeight : windowHeight;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n let fromScaleX = fromWidth / toWidth;\n let fromScaleY = fromHeight / toHeight;\n\n const shouldFadeOut = (\n [MediaViewerOrigin.Inline, MediaViewerOrigin.ScheduledInline].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n ) || (\n [MediaViewerOrigin.Album, MediaViewerOrigin.ScheduledAlbum].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n );\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n if (fromScaleX > fromScaleY) {\n fromScaleX = fromScaleY;\n } else if (fromScaleY > fromScaleX) {\n fromScaleY = fromScaleX;\n }\n }\n\n const ghost = createGhost(bestImageData || toImage, origin === MediaViewerOrigin.ProfileAvatar);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n\n requestAnimationFrame(() => {\n document.body.classList.add('ghost-animating');\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n if (shouldFadeOut) {\n ghost.style.opacity = '0';\n }\n\n applyShape(ghost, origin);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n document.body.removeChild(ghost);\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nfunction createGhost(source: string | HTMLImageElement | HTMLVideoElement, shouldAppendProfileInfo = false) {\n const ghost = document.createElement('div');\n ghost.classList.add('ghost');\n\n const img = new Image();\n\n if (typeof source === 'string') {\n img.src = source;\n } else if (source instanceof HTMLVideoElement) {\n img.src = source.poster;\n } else {\n img.src = source.src;\n }\n\n ghost.appendChild(img);\n\n if (shouldAppendProfileInfo) {\n ghost.classList.add('ProfileInfo');\n const profileInfo = document.querySelector('#RightColumn .ProfileInfo .info');\n if (profileInfo) {\n ghost.appendChild(profileInfo.cloneNode(true));\n }\n }\n\n return ghost;\n}\n\nfunction uncover(realWidth: number, realHeight: number, top: number, left: number, width: number, height: number) {\n if (realWidth === realHeight) {\n const size = Math.max(width, height) * (realWidth / realHeight);\n left -= (size - width) / 2;\n top -= (size - height) / 2;\n width = size;\n height = size;\n } else if (realWidth > realHeight) {\n const srcWidth = width;\n width = height * (realWidth / realHeight);\n left -= (width - srcWidth) / 2;\n } else if (realHeight > realWidth) {\n const srcHeight = height;\n height = width * (realHeight / realWidth);\n top -= (height - srcHeight) / 2;\n }\n\n return {\n top, left, width, height,\n };\n}\n\nfunction isElementInViewport(el: HTMLElement) {\n if (el.style.display === 'none') {\n return false;\n }\n\n const rect = el.getBoundingClientRect();\n const { height: windowHeight } = windowSize.get();\n\n return (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n}\n\nfunction isMessageImageFullyVisible(container: HTMLElement, imageEl: HTMLElement) {\n const messageListElement = document.querySelector('.active > .MessageList')!;\n let imgOffsetTop = container.offsetTop + imageEl.closest('.content-inner, .WebPage')!.offsetTop;\n if (container.id.includes('album-media-')) {\n imgOffsetTop += container.parentElement!.offsetTop + container.closest('.Message')!.offsetTop;\n }\n\n return imgOffsetTop > messageListElement.scrollTop\n && imgOffsetTop + imageEl.offsetHeight < messageListElement.scrollTop + messageListElement.offsetHeight;\n}\n\nfunction getTopOffset(hasFooter: boolean) {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n let topOffsetRem = 4.125;\n if (hasFooter) {\n topOffsetRem += mql.matches ? 0.875 : 3.375;\n }\n\n return topOffsetRem * REM;\n}\n\nfunction applyStyles(element: HTMLElement, styles: Record) {\n Object.assign(element.style, styles);\n}\n\nfunction getNodes(origin: MediaViewerOrigin, message?: ApiMessage) {\n let containerSelector;\n let mediaSelector;\n\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n containerSelector = `.active > .MessageList #album-media-${message!.id}`;\n mediaSelector = '.full-media';\n break;\n\n case MediaViewerOrigin.SharedMedia:\n containerSelector = `#shared-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.SearchResult:\n containerSelector = `#search-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n containerSelector = '.MiddleHeader .ChatInfo .Avatar';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ProfileAvatar:\n containerSelector = '#RightColumn .ProfileInfo .active .ProfilePhoto';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ScheduledInline:\n case MediaViewerOrigin.Inline:\n default:\n containerSelector = `.active > .MessageList #message${message!.id}`;\n mediaSelector = '.message-content .full-media, .message-content .thumbnail';\n }\n\n const container = document.querySelector(containerSelector)!;\n const mediaEls = container && container.querySelectorAll(mediaSelector);\n\n return {\n container,\n mediaEl: mediaEls && mediaEls[mediaEls.length - 1],\n };\n}\n\nfunction applyShape(ghost: HTMLDivElement, origin: MediaViewerOrigin) {\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n case MediaViewerOrigin.Inline:\n case MediaViewerOrigin.ScheduledInline:\n ghost.classList.add('rounded-corners');\n break;\n\n case MediaViewerOrigin.SharedMedia:\n case MediaViewerOrigin.ProfileAvatar:\n case MediaViewerOrigin.SearchResult:\n (ghost.firstChild as HTMLElement).style.objectFit = 'cover';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n ghost.classList.add('circle');\n break;\n }\n}\n\nfunction clearShape(ghost: HTMLDivElement) {\n (ghost.firstChild as HTMLElement).style.objectFit = 'default';\n ghost.classList.remove('rounded-corners', 'circle');\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../api/types';\n\nimport { getSenderTitle, isChatPrivate } from '../../modules/helpers';\nimport { formatMediaDateTime } from '../../util/dateFormat';\nimport renderText from '../common/helpers/renderText';\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from '../common/Avatar';\n\nimport './SenderInfo.scss';\n\ntype OwnProps = {\n chatId?: number;\n messageId?: number;\n isAvatar?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst SenderInfo: FC = ({\n chatId, messageId, sender, isAvatar, message, closeMediaViewer, focusMessage,\n}) => {\n const handleFocusMessage = useCallback(() => {\n closeMediaViewer();\n focusMessage({ chatId, messageId });\n }, [chatId, focusMessage, messageId, closeMediaViewer]);\n\n useLang();\n\n if (!sender || (!message && !isAvatar)) {\n return undefined;\n }\n\n const isFromChat = sender.id < 0;\n const senderTitle = getSenderTitle(sender);\n\n return (\n
\n {isFromChat ? (\n \n ) : (\n \n )}\n
\n
\n {senderTitle && renderText(senderTitle)}\n
\n
\n {isAvatar ? 'Profile photo' : formatMediaDateTime(message!.date * 1000)}\n
\n
\n
\n );\n};\n\nexport default withGlobal(\n (global, { chatId, messageId, isAvatar }): StateProps => {\n if (isAvatar && chatId) {\n return {\n sender: isChatPrivate(chatId) ? selectUser(global, chatId) : selectChat(global, chatId),\n };\n }\n\n if (!messageId || !chatId) {\n return {};\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n message,\n sender: message && selectSender(global, message),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['closeMediaViewer', 'focusMessage']),\n)(SenderInfo);\n","import React, {\n FC, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport download from '../../util/download';\nimport { getMessageMediaHash } from '../../modules/helpers';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './MediaViewerActions.scss';\n\ntype OwnProps = {\n mediaData?: string;\n isVideo: boolean;\n isZoomed: boolean;\n message?: ApiMessage;\n fileName?: string;\n isAvatar?: boolean;\n onCloseMediaViewer: NoneToVoidFunction;\n onForward: NoneToVoidFunction;\n onZoomToggle: NoneToVoidFunction;\n};\n\nconst MediaViewerActions: FC = ({\n mediaData,\n isVideo,\n isZoomed,\n message,\n fileName,\n isAvatar,\n onCloseMediaViewer,\n onForward,\n onZoomToggle,\n}) => {\n const [isVideoDownloadAllowed, setIsVideoDownloadAllowed] = useState(false);\n const videoMediaHash = isVideo && message ? getMessageMediaHash(message, 'download') : undefined;\n const {\n mediaData: videoBlobUrl, downloadProgress,\n } = useMediaWithDownloadProgress(videoMediaHash, !isVideoDownloadAllowed);\n\n // Download with browser when fully loaded\n useEffect(() => {\n if (isVideoDownloadAllowed && videoBlobUrl) {\n download(videoBlobUrl, fileName!);\n setIsVideoDownloadAllowed(false);\n }\n }, [fileName, videoBlobUrl, isVideoDownloadAllowed]);\n\n // Cancel download on slide change\n useEffect(() => {\n setIsVideoDownloadAllowed(false);\n }, [videoMediaHash]);\n\n const handleVideoDownloadClick = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setIsVideoDownloadAllowed((isAllowed) => !isAllowed);\n }, []);\n\n const lang = useLang();\n\n const MenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n if (IS_MOBILE_SCREEN) {\n return (\n
\n \n {!isAvatar && (\n \n {lang('Forward')}\n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? `${Math.round(downloadProgress * 100)}% Downloading...` : 'Download'}\n \n ) : (\n \n {lang('AccActionDownload')}\n \n )}\n \n {isVideoDownloadAllowed && }\n
\n );\n }\n\n return (\n
\n {!isAvatar && (\n <>\n \n \n \n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? (\n \n ) : (\n \n )}\n \n ) : (\n \n \n \n )}\n \n \n \n \n \n \n
\n );\n};\n\nexport default MediaViewerActions;\n","import React, { FC, useEffect, useState } from '../../lib/teact/teact';\nimport { throttle } from '../../util/schedulers';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport { REM } from '../common/helpers/mediaDimensions';\n\nimport './MediaViewerFooter.scss';\n\nconst RESIZE_THROTTLE_MS = 500;\n\ntype OwnProps = {\n text: TextPart | TextPart[];\n onClick: () => void;\n isHideable: boolean;\n};\n\nconst MediaViewerFooter: FC = ({ text = '', isHideable, onClick }) => {\n const [isMultiline, setIsMultiline] = useState(false);\n useEffect(() => {\n const footerContent = document.querySelector('.MediaViewerFooter .media-text') as HTMLDivElement | null;\n\n const checkIsMultiline = () => {\n const height = footerContent ? footerContent.clientHeight : 0;\n\n setIsMultiline(height > REM * 2);\n };\n\n // First run for initial detection of multiline footer text\n checkIsMultiline();\n\n const handleResize = throttle(checkIsMultiline, RESIZE_THROTTLE_MS, true);\n\n window.addEventListener('resize', handleResize, false);\n\n return () => {\n window.removeEventListener('resize', handleResize, false);\n };\n }, []);\n\n function stopEvent(e: React.MouseEvent) {\n if (text) {\n e.stopPropagation();\n }\n }\n\n return (\n
\n {text && (\n
\n

{text}

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

Sorry, nothing found.

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

{getReadableErrorText(error)}

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

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

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

{lang('AreYouSureDeleteSingleMessage')}

\n {willDeleteForCurrentUserOnly && (\n

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

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

This will delete it for everyone in this chat.

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

{lang('PinMessageAlertTitle')}

\n
\n );\n }\n\n function renderMessage() {\n if (isChannel) {\n return

{lang('PinMessageAlertChannel')}

;\n }\n\n if (isGroup || isSuperGroup) {\n return

{lang('PinMessageAlert')}

;\n }\n\n return

{lang('PinMessageAlertChat')}

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

{lang('UnpinAllMessages')}

\n
\n );\n }\n\n function renderMessage() {\n return

Do you want to unpin all {pinnedMessagesCount} messages in this chat?

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

{lang('AreYouSureDeleteFewMessages')}

\n {willDeleteForCurrentUserOnly && (\n

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

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

This will delete them for everyone in this chat.

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

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

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

{renderText(getChatTitle(chat, privateChatUser))}

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

\n {localResults.length > LESS_LIST_ITEMS_AMOUNT && (\n {shouldShowMoreLocal ? 'Show less' : 'Show more'}\n )}\n Contacts and Chats\n

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

\n {globalResults.length > LESS_LIST_ITEMS_AMOUNT && (\n {shouldShowMoreGlobal ? 'Show less' : 'Show more'}\n )}\n Global Search\n

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

{lang('SearchMessages')}

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

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

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

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

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

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

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

{lang('EditProfile')}

;\n case SettingsScreens.General:\n return

{lang('General')}

;\n case SettingsScreens.Notifications:\n return

{lang('Notifications')}

;\n case SettingsScreens.Privacy:\n return

{lang('PrivacySettings')}

;\n case SettingsScreens.Language:\n return

{lang('Language')}

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

{lang('ChatBackground')}

;\n case SettingsScreens.GeneralChatBackgroundColor:\n return

{lang('SetColor')}

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

{lang('PrivacyPhone')}

;\n case SettingsScreens.PrivacyLastSeen:\n return

{lang('PrivacyLastSeen')}

;\n case SettingsScreens.PrivacyProfilePhoto:\n return

{lang('Privacy.ProfilePhoto')}

;\n case SettingsScreens.PrivacyForwarding:\n return

{lang('PrivacyForwards')}

;\n case SettingsScreens.PrivacyGroupChats:\n return

{lang('AutodownloadGroupChats')}

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

{lang('AlwaysShareWith')}

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

{lang('NeverShareWith')}

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

{lang('SessionsTitle')}

;\n case SettingsScreens.PrivacyBlockedUsers:\n return

{lang('BlockedUsers')}

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

{lang('TwoStepVerification')}

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

{lang('EnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return

{lang('PleaseReEnterPassword')}

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

{lang('PasswordHint')}

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

{lang('RecoveryEmailTitle')}

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

Recovery Email Code

;\n case SettingsScreens.TwoFaCongratulations:\n return

{lang('TwoStepVerificationPasswordSet')}

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

{lang('PleaseEnterCurrentPassword')}

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

{lang('Filters')}

;\n case SettingsScreens.FoldersCreateFolder:\n return

{lang('FilterNew')}

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

{lang('FilterEdit')}

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

{lang('FilterInclude')}

\n ) : (\n

{lang('FilterExclude')}

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

{lang('SETTINGS')}

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

{getUserFullName(currentUser)}

\n

{formatPhoneNumberWithCode(currentUser.phoneNumber)}

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

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

\n
\n\n
\n

{lang('Username')}

\n\n \n\n

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

\n {username && (\n

\n This link opens a chat with you:
\n https://t.me/{username}\n

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

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

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

{lang('Filters')}

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

\n You have no folders yet.\n

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

{lang('FilterRecommended')}

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

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

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

\n {state.error}\n

\n )}\n\n

{lang('FilterInclude')}

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

{lang('FilterExclude')}

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

{lang(type.title)}

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

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

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

{lang('FilterChatTypes')}

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

{lang('FilterChats')}

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

Sorry, nothing found.

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

{lang('SETTINGS')}

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

\n Animation Level\n

\n

Choose the desired animations amount.

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

{lang('Keyboard')}

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

{lang('AutoDownloadMedia')}

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

{lang('AutoplayMedia')}

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

{lang('AccDescrStickers')}

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

{lang('AutodownloadPrivateChats')}

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

{lang('FilterGroups')}

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

{lang('FilterChannels')}

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

{lang('PhoneOther')}

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

{lang('PrivacyTitle')}

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

{headerText}

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

{descriptionText}

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

{lang('PrivacyExceptions')}

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

{lang('AuthSessions.CurrentSession')}

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

Other Sessions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{lang('GroupAddMembers')}

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

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

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

{lang('DescriptionInfo')}

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

{renderedError}

\n )}\n\n

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

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

{lang('ArchivedChats')}

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

\n Please choose the correct answer\n

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

Options

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

Solution

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

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

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

{stickerSet.title}

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

{title && renderText(title)}

\n \n
\n
\n {renderText(text, ['emoji', 'highlight'], { highlight: query })}\n
\n
\n
\n );\n };\n\n return (\n \n

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

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

{set.title}

\n

{set.count} stickers

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

Nothing found.

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

{lang('NoGIFsFound')}

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

{summary.question}

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

{lang('ChannelPermissionsHeader')}

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

{lang('PrivacyExceptions')}

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

{lang('NoBlockedGroup2')}

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

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

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

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

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

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

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

{lang('DiscussionChannelHelp')}

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

{lang('DiscussionChannelHelp2')}

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

{lang('UserRestrictionsCanDo')}

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

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

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

Actions

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

Admins

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

{lang('EditAdminWhatCanDo')}

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

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

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

Select shipping method

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

{ text }

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

\n { data }\n

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

{error.description || 'Error'}

\n {error.description || 'Error'}\n \n OK\n \n
\n );\n }\n\n function renderModalContent(cuurentStep: PaymentStep) {\n switch (cuurentStep) {\n case PaymentStep.ShippingInfo:\n return (\n \n );\n case PaymentStep.Shipping:\n return (\n \n );\n case PaymentStep.PaymentInfo:\n return (\n \n );\n case PaymentStep.Checkout:\n return (\n \n );\n default:\n return undefined;\n }\n }\n\n const validateRequest = useCallback(() => {\n const { saveInfo } = paymentState;\n const requestInfo = getRequestInfo(paymentState);\n validateRequestedInfo({ requestInfo, saveInfo });\n }, [validateRequestedInfo, paymentState]);\n\n const sendCredentials = useCallback(() => {\n const credentials = getCredentials(paymentState);\n sendCredentialsInfo({\n credentials,\n });\n }, [sendCredentialsInfo, paymentState]);\n\n const sendForm = useCallback(() => {\n sendPaymentForm({\n shippingOptionId: paymentState.shipping,\n saveCredentials: paymentState.saveCredentials,\n });\n }, [sendPaymentForm, paymentState]);\n\n const setStep = useCallback((nextStep) => {\n setPaymentStep({ step: nextStep });\n }, [setPaymentStep]);\n\n const handleButtonClick = useCallback(() => {\n setIsLoading(true);\n switch (step) {\n case PaymentStep.ShippingInfo:\n return validateRequest();\n case PaymentStep.Shipping:\n return setStep(PaymentStep.PaymentInfo);\n case PaymentStep.PaymentInfo:\n return sendCredentials();\n case PaymentStep.Checkout:\n return sendForm();\n default:\n return () => {};\n }\n }, [step, validateRequest, setStep, sendCredentials, sendForm]);\n\n const modalHeader = useMemo(() => {\n switch (step) {\n case PaymentStep.ShippingInfo:\n return lang('PaymentShippingInfo');\n case PaymentStep.Shipping:\n return lang('PaymentShippingMethod');\n case PaymentStep.PaymentInfo:\n return lang('PaymentCardInfo');\n case PaymentStep.Checkout:\n return lang('PaymentCheckout');\n default:\n return '';\n }\n }, [step, lang]);\n\n const buttonText = useMemo(() => {\n switch (step) {\n case PaymentStep.Checkout:\n return `Pay ${currencySign}${(totalPrice / 100).toFixed(2)}`;\n default:\n return 'Next Step';\n }\n }, [step, totalPrice, currencySign]);\n\n if (isProviderError) {\n return (\n \n Sorry, Telegram T doesn't support payments with this provider yet.\n Please use one of our mobile apps to do this.\n \n OK\n \n \n );\n }\n\n return (\n \n
\n \n \n \n

{ modalHeader }

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

{lang('PaymentReceipt')}

\n
\n
\n \n
\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { receipt } = global.payment;\n const {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n } = (receipt || {});\n\n return {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n };\n },\n)(ReceiptModal));\n\nfunction getCheckoutInfo(paymentMethod?: string,\n info?:\n { phone?: string;\n name?: string;\n shippingAddress?: ApiShippingAddress;\n },\n shippingMethod?: string) {\n if (!info) {\n return { paymentMethod };\n }\n const { shippingAddress } = info;\n const fullAddress = shippingAddress && shippingAddress.streetLine1\n ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}`\n : undefined;\n const { phone, name } = info;\n return {\n paymentMethod,\n paymentProvider: 'Stripe',\n shippingAddress: fullAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n
\n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/3.4cc830a94ce5c77c6a75.css b/dist/3.4181bafcca8da716a4b3.css similarity index 100% rename from dist/3.4cc830a94ce5c77c6a75.css rename to dist/3.4181bafcca8da716a4b3.css diff --git a/dist/3.4cc830a94ce5c77c6a75.js b/dist/3.4181bafcca8da716a4b3.js similarity index 54% rename from dist/3.4cc830a94ce5c77c6a75.js rename to dist/3.4181bafcca8da716a4b3.js index d29d542c..7a3dbc69 100644 --- a/dist/3.4cc830a94ce5c77c6a75.js +++ b/dist/3.4181bafcca8da716a4b3.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{186:function(e,t,a){},187:function(e,t,a){},188:function(e,t,a){},200:function(e,t,a){},201:function(e,t,a){},202:function(e,t,a){},205:function(e,t,a){},206:function(e,t,a){},207:function(e,t,a){},211:function(e,t,a){},212:function(e,t,a){},214:function(e,t,a){},217:function(e,t,a){},218:function(e,t,a){},219:function(e,t,a){},220:function(e,t,a){},221:function(e,t,a){},222:function(e,t,a){},223:function(e,t,a){},224:function(e,t,a){},225:function(e,t,a){},226:function(e,t,a){},227:function(e,t,a){},229:function(e,t,a){},230:function(e,t,a){},231:function(e,t,a){},232:function(e,t,a){},233:function(e,t,a){},234:function(e,t,a){},235:function(e,t,a){},239:function(e,t,a){},240:function(e,t,a){},241:function(e,t,a){},91:function(e,t,a){"use strict";a.r(t),a.d(t,"Main",(function(){return wn}));var s=a(2),n=a(1),c=a(0),r=(a(74),a(39)),o=a(6);window.addEventListener("popstate",e=>{if(!e.state)return;const{chatId:t,threadId:a,messageListType:n}=e.state;Object(s.d)().openChat({id:t,threadId:a,type:n,noPushState:!0})}),Object(s.b)("openChat",(e,t,a)=>{const{id:n,threadId:c=-1,type:i="thread",noPushState:l}=a,d=Object(o.y)(e);return d&&d.chatId===n&&d.threadId===c&&d.type===i||(e=Object(r.m)(e),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...n!==e.forwardMessages.toChatId&&{forwardMessages:{}}},Object(s.g)(e),l||window.history.pushState({chatId:n,threadId:c,messageListType:i},"")),Object(r.L)(e,n,c,i)}),Object(s.b)("openChatWithInfo",(e,t,a)=>{Object(s.g)({...e,isChatInfoShown:!0}),t.openChat(a)}),Object(s.b)("resetChatCreation",e=>({...e,chatCreation:void 0}));var i=a(4),l=a(19),d=a(3);let b;Object(s.b)("setScrollOffset",(e,t,a)=>{const{chatId:s,threadId:n,scrollOffset:c}=a;return Object(r.v)(e,s,n,"scrollOffset",c)}),Object(s.b)("setReplyingToId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i}=n;return Object(r.v)(e,c,i,"replyingToId",s)}),Object(s.b)("setEditingId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i,type:l}=n,d="scheduled"===l?"editingScheduledId":"editingId";return Object(r.v)(e,c,i,d,s)}),Object(s.b)("editLastMessage",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(!t||!a)return;const s=Object(o.m)(e,t),n=Object(o.Eb)(e,t,a);if(!s||!n)return;const c=Object(d.g)(n,t=>Boolean(s[t]&&Object(o.b)(e,s[t],a).canEdit));return c?Object(r.v)(e,t,a,"editingId",c):void 0}),Object(s.b)("openMediaViewer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i}=a;return{...e,mediaViewer:{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i},forwardMessages:{}}}),Object(s.b)("closeMediaViewer",e=>({...e,mediaViewer:{}})),Object(s.b)("openAudioPlayer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c}=a;return{...e,audioPlayer:{chatId:s,threadId:n,messageId:c}}}),Object(s.b)("closeAudioPlayer",e=>({...e,audioPlayer:{}})),Object(s.b)("openPollResults",(e,t,a)=>{const{chatId:n,messageId:c}=a;Object(o.V)(e)?n===e.pollResults.chatId&&c===e.pollResults.messageId||Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}}):window.setTimeout(()=>{const e=Object(s.e)();Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}})},450)}),Object(s.b)("closePollResults",e=>{Object(s.g)({...e,pollResults:{}})}),Object(s.b)("focusLastMessage",(e,t)=>{const a=Object(o.y)(e);if(!a)return;const{chatId:s,threadId:n}=a;let c;if(n===i.MAIN_THREAD_ID){const t=Object(o.f)(e,s);c=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.zb)(e,s,n);c=t?t.lastMessageId:void 0}c&&t.focusMessage({chatId:s,threadId:n,messageId:c,noHighlight:!0})}),Object(s.b)("focusMessage",(e,t,a)=>{const{chatId:n,threadId:c=i.MAIN_THREAD_ID,messageListType:d="thread",noHighlight:u,groupedId:m,groupedChatId:h}=a;let{messageId:O}=a;if(void 0!==m){const t=Object(o.I)(e,h,m);t&&t.length&&([O]=t)}const j=Object(o.y)(e),g=!j||n!==j.chatId||c!==j.threadId||d!==j.type;b&&(clearTimeout(b),b=void 0),b=window.setTimeout(()=>{let e=Object(s.e)();e=Object(r.N)(e),e=Object(r.M)(e),Object(s.g)(e)},2e3),e=Object(r.N)(e,n,O,u),e=Object(r.M)(e,void 0),g&&(e=Object(r.M)(e,l.b.Static));const f=Object(o.Eb)(e,n,c);if(f&&f.includes(O))return Object(s.g)(e),void t.openChat({id:n,threadId:c});if(g&&(e=Object(r.v)(e,n,c,"viewportIds",void 0)),e=Object(r.v)(e,n,c,"outlyingIds",void 0),f&&!g){const t=O>f[0]?l.b.Down:l.b.Up;e=Object(r.M)(e,t)}Object(s.g)(e),t.openChat({id:n,threadId:c}),t.loadViewportMessages()}),Object(s.b)("openForwardMenu",(e,t,a)=>{const{fromChatId:s,messageIds:n,groupedId:c}=a;let r;return c&&(r=Object(o.Z)(e,s,c)),{...e,forwardMessages:{fromChatId:s,messageIds:r||n,isModalShown:!0}}}),Object(s.b)("exitForwardMode",e=>{Object(s.g)({...e,forwardMessages:{}})}),Object(s.b)("setForwardChatId",(e,t,a)=>{const{id:n}=a;Object(s.g)({...e,forwardMessages:{...e.forwardMessages,toChatId:n,isModalShown:!1}}),t.openChat({id:n}),t.closeMediaViewer()}),Object(s.b)("openForwardMenuForSelectedMessages",(e,t)=>{if(!e.selectedMessages)return;const{chatId:a,messageIds:s}=e.selectedMessages;t.openForwardMenu({fromChatId:a,messageIds:s})}),Object(s.b)("enterMessageSelectMode",(e,t,a)=>{const{messageId:s}=a||{},n=Object(o.r)(e);return n?Object(r.l)(e,n.id,s):e}),Object(s.b)("toggleMessageSelection",(e,t,a)=>{const{messageId:s,groupedId:n,childMessageIds:c,withShift:i}=a,l=Object(o.y)(e);if(!l)return;const{chatId:d,threadId:b,type:u}=l;return Object(r.E)(e,d,b,u,s,n,c,i)}),Object(s.b)("exitMessageSelectMode",r.m),Object(s.b)("openPollModal",e=>({...e,isPollModalOpen:!0})),Object(s.b)("closePollModal",e=>({...e,isPollModalOpen:!1}));Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{query:s}=a,{chatId:n}=e.globalSearch;return Object(r.P)(e,{globalResults:{},localResults:{},resultsByType:void 0,...s?{fetchingStatus:{chats:!n,messages:!0}}:{fetchingStatus:void 0},query:s})}),Object(s.b)("addRecentlyFoundChatId",(e,t,a)=>{const{id:s}=a,{recentlyFoundChatIds:n}=e.globalSearch;if(!n)return Object(r.P)(e,{recentlyFoundChatIds:[s]});const c=n.filter(e=>e!==s);return c.unshift(s),c.length>10&&c.pop(),Object(r.P)(e,{recentlyFoundChatIds:c})}),Object(s.b)("clearRecentlyFoundChats",e=>Object(r.P)(e,{recentlyFoundChatIds:void 0})),Object(s.b)("setGlobalSearchContent",(e,t,a)=>{const{content:s}=a;return Object(r.Q)(e,s)}),Object(s.b)("setGlobalSearchChatId",(e,t,a)=>{const{id:s}=a;return Object(r.P)(e,{chatId:s,query:void 0,resultsByType:void 0})});var u=a(45),m=a(5);Object(s.b)("openLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return Object(r.W)(e,t,a,!0)}),Object(s.b)("closeLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return e=Object(r.W)(e,t,a,!1),e=Object(r.s)(e,t,a,void 0)}),Object(s.b)("setLocalTextSearchQuery",(e,t,a)=>{const{chatId:s,threadId:n}=Object(o.y)(e)||{};if(!s||!n)return;const{query:c}=a,i=Object(m.a)(s,n),{query:l}=e.localTextSearch.byChatThreadKey[i]||{};return c!==l&&(e=Object(r.s)(e,s,n,u.a)),e=Object(r.W)(e,s,n,!0,c)}),Object(s.b)("setLocalMediaSearchType",(e,t,a)=>{const{chatId:s}=Object(o.y)(e)||{};if(!s)return;const{mediaType:n}=a;return Object(r.V)(e,s,n)}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,stickers:{...e.stickers,search:{query:s,resultIds:void 0}}}}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,gifs:{...e.gifs,search:{query:s,offsetId:void 0,results:void 0}}}}),Object(s.b)("openUserInfo",(e,t,a)=>{const{id:s}=a;t.openChat({id:s})});Object(s.b)("openChat",e=>Object(r.db)(e,void 0)),Object(s.b)("setSettingOption",(e,t,a)=>Object(r.u)(e,a));var h=a(7),O=a(159);Object(s.b)("toggleChatInfo",e=>({...e,isChatInfoShown:!e.isChatInfoShown})),Object(s.b)("toggleManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}}),Object(s.b)("closeManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}}),Object(s.b)("openChat",(e,t,a)=>{if(!h.f)return;const{id:s}=a;return{...e,isLeftColumnShown:void 0===s}}),Object(s.b)("toggleLeftColumn",e=>({...e,isLeftColumnShown:!e.isLeftColumnShown})),Object(s.b)("addRecentEmoji",(e,t,a)=>{const{emoji:s}=a,{recentEmojis:n}=e;if(!n)return{...e,recentEmojis:[s]};const c=n.filter(e=>e!==s);return c.unshift(s),c.length>18&&c.pop(),{...e,recentEmojis:c}}),Object(s.b)("addRecentSticker",(e,t,a)=>{const{sticker:s}=a,{recent:n}=e.stickers;if(!n)return{...e,stickers:{...e.stickers,recent:{hash:0,stickers:[s]}}};const c=n.stickers.filter(e=>e.id!==s.id);return c.unshift(s),{...e,stickers:{...e.stickers,recent:{...n,stickers:c}}}}),Object(s.b)("showNotification",(e,t,a)=>{const s=a,n=[...e.notifications],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,notifications:n}}),Object(s.b)("dismissNotification",e=>{const t=[...e.notifications];return t.pop(),{...e,notifications:t}}),Object(s.b)("showError",(e,t,a)=>{const{error:s}=a;if(!Object(O.a)(s))return e;const n=[...e.errors],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,errors:n}}),Object(s.b)("dismissError",e=>{const t=[...e.errors];return t.pop(),{...e,errors:t}}),Object(s.b)("openPaymentModal",(e,t,a)=>{const{messageId:s}=a;return{...e,payment:{...e.payment,messageId:s,isPaymentModalOpen:!0}}}),Object(s.b)("closePaymentModal",e=>{const t=Object(r.g)(e);return Object(r.h)(t)});a(75);var j=a(10),g=a(9);const f=Object(g.g)(e=>e(),1e3,!0),p=Object(g.g)(e=>e(),3e3,!0),I=Object(g.a)(e=>e(),500,!1,!0);async function v(e,t,a){const c=await Object(j.a)("fetchChats",{limit:n.i,offsetDate:a,archived:"archived"===e,withPinned:void 0===Object(s.e)().chats.orderedPinnedIds[e]});if(!c)return;const{chatIds:o}=c;o.length>0&&o[0]===t&&o.shift();let l=Object(s.e)();l=Object(r.e)(l,Object(d.c)(c.users,"id")),l=Object(r.K)(l,Object(d.c)(c.chats,"id")),l=Object(r.G)(l,e,o),l=Object(r.H)(l,e,c),Object.keys(c.draftsById).map(Number).forEach(e=>{l=Object(r.v)(l,e,i.MAIN_THREAD_ID,"draft",c.draftsById[e])}),Object.keys(c.replyingToById).map(Number).forEach(e=>{l=Object(r.v)(l,e,i.MAIN_THREAD_ID,"replyingToId",c.replyingToById[e])}),0!==o.length||l.chats.isFullyLoaded[e]||(l={...l,chats:{...l.chats,isFullyLoaded:{...l.chats.isFullyLoaded,[e]:!0}}}),Object(s.g)(l)}async function y(e){const t=await Object(j.a)("fetchFullChat",e);if(!t)return;const{users:a,fullInfo:n}=t;let c=Object(s.e)();a&&(c=Object(r.e)(c,Object(d.c)(a,"id"))),c=Object(r.F)(c,e.id,{fullInfo:n}),Object(s.g)(c)}async function C(e,t,a){const n=Object(s.e)(),c=Object(o.h)(n,t);if(c&&!c.isMin)return void(a?e.focusMessage({chatId:c.id,messageId:a}):e.openChat({id:c.id}));const i=Object(o.r)(n);e.openChat({id:-1});const l=await Object(j.a)("getChatByUsername",t);if(!l)return i&&e.openChat({id:i.id}),void e.showNotification({message:"User does not exist"});Object(s.g)(Object(r.F)(Object(s.e)(),l.id,l)),a?e.focusMessage({chatId:l.id,messageId:a}):e.openChat({id:l.id})}Object(s.b)("preloadTopChatMessages",(e,t)=>{(async()=>{const a=[];for(let c=0;ce!==l&&!a.includes(e));if(!u)return;a.push(u.id),t.loadViewportMessages({chatId:u.id,threadId:i.MAIN_THREAD_ID}),h.k&&t.loadPinnedMessages({chatId:u.id})}})()}),Object(s.b)("openChat",(e,t,a)=>{const{id:s,threadId:n}=a,{currentUserId:c}=e,r=Object(o.f)(e,s);if(r&&r.hasUnreadMark&&t.toggleChatUnread({id:s}),r)Object(m.lb)(r)&&!r.isMin&&t.requestChatUpdate({chatId:s});else if(s===c)Object(j.a)("fetchChat",{type:"self"});else{const t=Object(o.Db)(e,s);t&&Object(j.a)("fetchChat",{type:"user",user:t})}if(n!==i.MAIN_THREAD_ID){Object(o.Bb)(e,s,n)||t.requestThreadInfoUpdate({chatId:s,threadId:n})}}),Object(s.b)("openSupportChat",(e,t)=>{const a=Object(o.xb)(e);t.openChat({id:a?a.id:-1}),a||(async()=>{const e=await Object(j.a)("fetchChat",{type:"support"});e&&t.openChat({id:e.chatId})})()}),Object(s.b)("openTipsChat",(e,t)=>{t.openChatByUsername({username:n.Ab})}),Object(s.b)("loadMoreChats",(e,t,a)=>{const{listType:s="active"}=a,n=e.chats.listIds[s];if(e.chats.isFullyLoaded[s])return;const c=n?n.map(t=>e.chats.byId[t]).filter(t=>Boolean(t&&t.lastMessage)&&!Object(o.M)(e,t.id)).sort((e,t)=>e.lastMessage.date-t.lastMessage.date)[0]:void 0;f(c?()=>v(s,c.id,c.lastMessage.date):()=>v(s))}),Object(s.b)("loadFullChat",(e,t,a)=>{const{chatId:s,force:n}=a,c=Object(o.f)(e,s);c&&(n?y(c):I(()=>y(c)))}),Object(s.b)("loadTopChats",()=>{p(()=>v("active"))}),Object(s.b)("requestChatUpdate",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);n&&Object(j.a)("requestChatUpdate",n)}),Object(s.b)("updateChatMutedState",(e,t,a)=>{const{chatId:s,isMuted:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatMutedState",{chat:c,isMuted:n})}),Object(s.b)("createChannel",(e,t,a)=>{const{title:n,about:c,photo:i,memberIds:d}=a;!async function(e,t,a,n){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const c=await Object(j.a)("createChannel",{title:e,about:a,users:t});if(!c)return;const{id:o,accessHash:i}=c;let d=Object(s.e)();d=Object(r.F)(d,o,c),d={...d,chatCreation:{...d.chatCreation,progress:c?l.a.Complete:l.a.Error}},Object(s.g)(d),Object(s.d)().openChat({id:o}),o&&i&&n&&await Object(j.a)("editChatPhoto",{chatId:o,accessHash:i,photo:n})}(n,d.map(t=>Object(o.Db)(e,t)).filter(Boolean),c,i)}),Object(s.b)("joinChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("joinChannel",{channelId:c,accessHash:r})}),Object(s.b)("leaveChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("leaveChannel",{channelId:c,accessHash:r})}),Object(s.b)("deleteChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("deleteChannel",{channelId:c,accessHash:r})}),Object(s.b)("createGroupChat",(e,t,a)=>{const{title:n,memberIds:c,photo:i}=a;!async function(e,t,a){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const n=await Object(j.a)("createGroupChat",{title:e,users:t});if(!n)return;const{id:c}=n;let o=Object(s.e)();o=Object(r.F)(o,c,n),o={...o,chatCreation:{...o.chatCreation,progress:n?l.a.Complete:l.a.Error}},Object(s.g)(o),Object(s.d)().openChat({id:c}),c&&a&&await Object(j.a)("editChatPhoto",{chatId:c,photo:a})}(n,c.map(t=>Object(o.Db)(e,t)).filter(Boolean),i)}),Object(s.b)("toggleChatPinned",(e,t,a)=>{const{id:s,folderId:c}=a,r=Object(o.f)(e,s);if(r)if(c){const t=Object(o.i)(e,c);if(t){const a=!Object(o.M)(e,s,c),{pinnedChatIds:n,includedChatIds:r}=t,i=a?[s,...n||[]]:(n||[]).filter(e=>e!==s),l=[s,...r];Object(j.a)("editChatFolder",{id:c,folderUpdate:{...t,pinnedChatIds:i,includedChatIds:l}})}}else{const t=Object(o.j)(e,s),a=Object(o.M)(e,s,"archived"===t?n.g:void 0);Object(j.a)("toggleChatPinned",{chat:r,shouldBePinned:!a})}}),Object(s.b)("toggleChatArchived",(e,t,a)=>{const{id:s}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleChatArchived",{chat:c,folderId:Object(m.gb)(c)?0:n.g})}),Object(s.b)("loadChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,...e}})}}()}),Object(s.b)("loadRecommendedChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchRecommendedChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,recommended:e}})}}()}),Object(s.b)("editChatFolder",(e,t,a)=>{const{id:s,folderUpdate:n}=a,c=Object(o.i)(e,s);c&&Object(j.a)("editChatFolder",{id:s,folderUpdate:{id:s,emoticon:c.emoticon,pinnedChatIds:c.pinnedChatIds,...n}})}),Object(s.b)("addChatFolder",(e,t,a)=>{const{folder:c}=a,{orderedIds:r}=e.chatFolders;!async function(e,t){const{id:a,description:n,...c}=e;if(await Object(j.a)("editChatFolder",{id:t+1,folderUpdate:{id:t+1,...c}}),!n)return;const r=Object(s.e)(),{recommended:o}=r.chatFolders;o&&Object(s.g)({...r,chatFolders:{...r.chatFolders,recommended:o.filter(({id:e})=>e!==a)}})}(c,r&&r.length?Math.max.apply(Math.max,r):n.g)}),Object(s.b)("deleteChatFolder",(e,t,a)=>{const{id:s}=a;Object(o.i)(e,s)&&async function(e){await Object(j.a)("deleteChatFolder",e)}(s)}),Object(s.b)("toggleChatUnread",(e,t,a)=>{const{id:s}=a,n=Object(o.f)(e,s);n&&(n.unreadCount?Object(j.a)("markMessageListRead",{chat:n,threadId:i.MAIN_THREAD_ID}):Object(j.a)("toggleDialogUnread",{chat:n,hasUnreadMark:!n.hasUnreadMark}))}),Object(s.b)("openTelegramLink",(e,t,a)=>{const{url:s}=a;let c=n.gb.exec(s);if(c){const e=c[1];(async()=>{const a=await Object(j.a)("openChatByInvite",e);a&&t.openChat({id:a.id})})()}else{c=n.hb.exec(s);const e=c[1],a=c[2]?Number(c[2]):void 0;C(t,e,a)}}),Object(s.b)("openChatByUsername",(e,t,a)=>{const{username:s}=a;C(t,s)}),Object(s.b)("togglePreHistoryHidden",(e,t,a)=>{const{chatId:s,isEnabled:n}=a;let c=Object(o.f)(e,s);c&&(async()=>{if(Object(m.hb)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}Object(j.a)("togglePreHistoryHidden",{chat:c,isEnabled:n})})()}),Object(s.b)("updateChatDefaultBannedRights",(e,t,a)=>{const{chatId:s,bannedRights:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatDefaultBannedRights",{chat:c,bannedRights:n})}),Object(s.b)("updateChatMemberBannedRights",(e,t,a)=>{const{chatId:n,userId:c,bannedRights:i}=a;let l=Object(o.f)(e,n);const d=Object(o.Db)(e,c);l&&d&&(async()=>{if(Object(m.hb)(l)){if(l=await Object(j.a)("migrateChat",l),!l)return;t.openChat({id:l.id})}await Object(j.a)("updateChatMemberBannedRights",{chat:l,user:d,bannedRights:i});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{members:b,kickedMembers:u}=a.fullInfo,h=!!i.viewMessages,O=!Object.keys(i).length;Object(s.g)(Object(r.F)(e,n,{fullInfo:{...a.fullInfo,...b&&h&&{members:b.filter(e=>e.userId!==c)},...b&&!h&&{members:b.map(e=>e.userId===c?{...e,bannedRights:i}:e)},...O&&u&&{kickedMembers:u.filter(e=>e.userId!==c)}}}))})()}),Object(s.b)("updateChatAdmin",(e,t,a)=>{const{chatId:n,userId:c,adminRights:i,customTitle:l}=a;let d=Object(o.f)(e,n);const b=Object(o.Db)(e,c);d&&b&&(async()=>{if(Object(m.hb)(d)){if(d=await Object(j.a)("migrateChat",d),!d)return;t.openChat({id:d.id})}await Object(j.a)("updateChatAdmin",{chat:d,user:b,adminRights:i,customTitle:l});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{adminMembers:u}=a.fullInfo,h=!Object.keys(i).length;Object(s.g)(Object(r.F)(e,n,{fullInfo:{...a.fullInfo,...u&&h&&{adminMembers:u.filter(e=>e.userId!==c)},...u&&!h&&{adminMembers:u.map(e=>e.userId===c?{...e,adminRights:i,customTitle:l}:e)}}}))})()}),Object(s.b)("updateChat",(e,t,a)=>{const{chatId:n,title:c,about:i,photo:d}=a,b=Object(o.f)(e,n);b&&(async()=>{Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.InProgress)),await Promise.all([b.title!==c?Object(j.a)("updateChatTitle",b,c):void 0,b.fullInfo&&b.fullInfo.about!==i?Object(j.a)("updateChatAbout",b,i):void 0,d?Object(j.a)("editChatPhoto",{chatId:n,accessHash:b.accessHash,photo:d}):void 0]),Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.Complete))})()}),Object(s.b)("toggleSignatures",(e,t,a)=>{const{chatId:s,isEnabled:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleSignatures",{chat:c,isEnabled:n})}),Object(s.b)("loadGroupsForDiscussion",()=>{(async()=>{const e=await Object(j.a)("fetchGroupsForDiscussion");if(!e)return;const t=e.reduce((e,t)=>(t&&(e[t.id]=t),e),{}),a=Object(r.c)(Object(s.e)(),t);Object(s.g)({...a,chats:{...a.chats,forDiscussionIds:Object.keys(t).map(Number)}})})()}),Object(s.b)("linkDiscussionGroup",(e,t,a)=>{const{channelId:s,chatId:n}=a,c=Object(o.f)(e,s);let r=Object(o.f)(e,n);c&&r&&(async()=>{if(Object(m.hb)(r)){if(r=await Object(j.a)("migrateChat",r),!r)return;t.openChat({id:r.id})}let{fullInfo:e}=r;if(!e){const t=await Object(j.a)("fetchFullChat",r);if(!t)return;e=t.fullInfo}e.isPreHistoryHidden&&await Object(j.a)("togglePreHistoryHidden",{chat:r,isEnabled:!1}),Object(j.a)("setDiscussionGroup",{channel:c,chat:r})})()}),Object(s.b)("unlinkDiscussionGroup",(e,t,a)=>{const{channelId:s}=a,n=Object(o.f)(e,s);if(!n)return;let c;n.fullInfo&&n.fullInfo.linkedChatId&&(c=Object(o.f)(e,n.fullInfo.linkedChatId)),(async()=>{await Object(j.a)("setDiscussionGroup",{channel:n}),c&&y(c)})()}),Object(s.b)("loadMoreMembers",e=>{(async()=>{const{chatId:t}=Object(o.y)(e)||{},a=t?Object(o.f)(e,t):void 0;if(!a||Object(m.hb)(a))return;const n=a.fullInfo&&a.fullInfo.members&&a.fullInfo.members.length||void 0,c=await Object(j.a)("fetchMembers",a.id,a.accessHash,"recent",n);if(!c)return;const{members:i,users:l}=c;i&&i.length&&(e=Object(s.e)(),e=Object(r.e)(e,Object(d.c)(l,"id")),e=Object(r.F)(e,a.id,{fullInfo:{...a.fullInfo,members:[...(a.fullInfo||{}).members||[],...i||[]]}}),Object(s.g)(e))})()});var w=a(143);const E=new Map;async function M(e,t,a,c,i=!1,b=!1){const u=e.id;let m;switch(c){case l.e.Backwards:m=void 0;break;case l.e.Around:m=-(Math.round(n.U/2)+1);break;case l.e.Forwards:m=-(n.U+1)}const h=await Object(j.a)("fetchMessages",{chat:Object(o.Ab)(Object(s.e)(),u,t),offsetId:a,addOffset:m,limit:n.U,threadId:t});if(!h)return;const{messages:O,users:g,chats:f,threadInfos:p,firstMessageId:I}=h,v=Object(d.c)(O,"id"),y=Object.keys(v).map(Number);let C=Object(s.e)();C=Object(r.b)(C,u,v),C=i?Object(r.bb)(C,u,t,y):Object(r.T)(C,u,t,y),C=Object(r.e)(C,Object(d.c)(g,"id")),C=Object(r.c)(C,Object(d.c)(f,"id")),C=Object(r.jb)(C,u,p),I&&(C=Object(r.v)(C,u,t,"firstMessageId",I));let w=Object(o.X)(C,u,t);const E=Object(o.db)(C,u,t);if(i&&w&&E&&Object(d.b)(w,E)&&(C=Object(r.T)(C,u,t,E),w=Object(o.X)(C,u,t),C=Object(r.v)(C,u,t,"outlyingIds",void 0),i=!1),!b){const e=i?E:w,{newViewportIds:s}=S(e,a,c);C=Object(r.x)(C,u,t,s)}Object(s.g)(C)}function S(e,t,a){const{length:s}=e,c=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex((a,s)=>a===t||at)}(e,t):-1,r=a===l.e.Backwards?c:c+1||s,o=r-n.U,i=r+n.U-1,d=e.slice(Math.max(0,o),i+1);let b,u;switch(a){case l.e.Backwards:b=r>0,u=o>=0;break;case l.e.Forwards:b=r0,u=d.length===n.U}return{newViewportIds:d,areSomeLocal:b,areAllLocal:u}}async function k(e){let t;const a=e.attachment?(e,n)=>{E.has(n)||(t=n,E.set(n,a));const c=Object(s.e)();Object(s.g)({...c,fileUploads:{byMessageLocalId:{...c.fileUploads.byMessageLocalId,[n]:{progress:e}}}})}:void 0;e.replyingTo&&await Object(g.f)();const n=Object(s.e)(),c=Object(o.y)(n);if(!c)return;const{threadId:r}=c;e.replyingTo||r===i.MAIN_THREAD_ID||(e.replyingTo=Object(o.Bb)(n,e.chat.id,r)),await Object(j.a)("sendMessage",e,a),a&&t&&E.delete(t)}Object(s.b)("loadViewportMessages",(e,t,a)=>{const{direction:s=l.e.Around,isBudgetPreload:c=!1}=a||{};let{chatId:i,threadId:d}=a||{};if(!i){const t=Object(o.y)(e);if(!t)return;i=t.chatId,d=t.threadId}const b=Object(o.f)(e,i);if(!b||b.isRestricted)return;const u=Object(o.Eb)(e,i,d),m=Object(o.X)(e,i,d),h=Object(o.db)(e,i,d);if(u&&u.length&&s!==l.e.Around){const a=s===l.e.Backwards?u[0]:u[u.length-1],n=Boolean(h),o=n?h:m,{newViewportIds:O,areSomeLocal:j,areAllLocal:g}=S(o,a,s);if(j&&(e=Object(r.x)(e,i,d,O)),async function(e,t,a,s,n,c,r,o){t||await M(n,c,o,r,a,s);s||(await Promise.resolve(),e.loadViewportMessages({chatId:n.id,threadId:c,direction:r,isBudgetPreload:!0}))}(t,g,n,c,b,d,s,a),c)return}else{const t=Object(o.H)(e,i)||Object(o.ib)(e,i,d),a=Boolean(t&&m&&!m.includes(t)),s=(a?h:m)||[],{newViewportIds:u,areSomeLocal:O,areAllLocal:j}=S(s,t,l.e.Around);O&&u.length>=n.U&&(e=Object(r.x)(e,i,d,u)),j||M(b,d,t,l.e.Around,a,c)}return e}),Object(s.b)("loadMessage",(e,t,a)=>{const{chatId:n,messageId:c,replyOriginForId:l}=a,b=Object(o.f)(e,n);b&&async function(e,t,a){const n=await Object(j.a)("fetchMessage",{chat:e,messageId:t});if(!n)return;if(n===i.MESSAGE_DELETED){if(a){let t=Object(s.e)();const n=Object(o.k)(t,e.id,a);t=Object(r.J)(t,e.id,a,{...n,replyToMessageId:void 0}),Object(s.g)(t)}return}let c=Object(s.e)();c=Object(r.J)(c,e.id,t,n.message),c=Object(r.e)(c,Object(d.c)(n.users,"id")),Object(s.g)(c)}(b,c,l)}),Object(s.b)("sendMessage",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:c,threadId:r,type:i}=s;if("scheduled"===i&&!a.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:a}};const l=Object(o.f)(e,c);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:c,threadId:r,value:!1});const b={...a,chat:l,replyingTo:Object(o.jb)(e,c,r),noWebPage:Object(o.bb)(e,c,r)},u=!a.attachments||a.attachments.length<=1,m=!u&&a.attachments&&a.attachments.length>1;if(u){const{attachments:e,...t}=b;k({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:a,...s}=b,c=Object(d.n)(a,n.K);for(let a=0;a0?o:void 0}),r.forEach(e=>{k({...s,attachment:e,groupedId:o})})}}else{const{text:e,entities:t,attachments:a,replyingTo:s,...n}=b;e&&k({...n,text:e,entities:t,replyingTo:s}),a.forEach(e=>{k({...n,attachment:e})})}}),Object(s.b)("editMessage",(e,t,a)=>{const{text:s,entities:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i,type:l}=c,d=Object(o.f)(e,r),b=Object(o.D)(e,r,i,l);d&&b&&(Object(j.a)("editMessage",{chat:d,message:b,text:s,entities:n}),t.setEditingId({messageId:void 0}))}),Object(s.b)("cancelSendingMessage",(e,t,a)=>{const{chatId:s,messageId:n}=a,c=Object(o.k)(e,s,n),r=c&&E.get(c.previousLocalId||c.id);r&&Object(j.b)(r),t.apiUpdate({"@type":"deleteMessages",ids:[n],chatId:s})}),Object(s.b)("saveDraft",(e,t,a)=>{const{chatId:s,threadId:n,draft:c}=a;if(!c)return;const{text:l,entities:d}=c,b=Object(o.f)(e,s);return n===i.MAIN_THREAD_ID&&Object(j.a)("saveDraft",{chat:b,text:l,entities:d,replyToMsgId:Object(o.jb)(e,s,n)}),Object(r.v)(e,s,n,"draft",c)}),Object(s.b)("clearDraft",(e,t,a)=>{const{chatId:s,threadId:n,localOnly:c}=a;if(!Object(o.B)(e,s,n))return;const l=Object(o.f)(e,s);return c||n!==i.MAIN_THREAD_ID||Object(j.a)("clearDraft",l),Object(r.v)(e,s,n,"draft",void 0)}),Object(s.b)("toggleMessageWebPage",(e,t,a)=>{const{chatId:s,threadId:n,noWebPage:c}=a;return Object(r.v)(e,s,n,"noWebPage",c)}),Object(s.b)("pinMessage",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageId:n,isUnpin:c,isOneSide:r,isSilent:i}=a;Object(j.a)("pinMessage",{chat:s,messageId:n,isUnpin:c,isOneSide:r,isSilent:i})}),Object(s.b)("unpinAllMessages",(e,t,a)=>{const n=Object(o.f)(e,a.chatId);n&&async function(e){await Object(j.a)("unpinAllMessages",{chat:e});let t=Object(s.e)();t=Object(r.v)(t,e.id,i.MAIN_THREAD_ID,"pinnedIds",[]),Object(s.g)(t)}(n)}),Object(s.b)("deleteMessages",(e,t,a)=>{const{messageIds:s,shouldDeleteForAll:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i}=c,l=Object(o.f)(e,r);Object(j.a)("deleteMessages",{chat:l,messageIds:s,shouldDeleteForAll:n});const d=Object(o.C)(e,r,i);s.includes(d)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteScheduledMessages",(e,t,a)=>{const{messageIds:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c}=n,r=Object(o.f)(e,c);Object(j.a)("deleteScheduledMessages",{chat:r,messageIds:s});const i=Object(o.E)(e,c);s.includes(i)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteHistory",(e,t,a)=>{const{chatId:s,maxId:n,shouldDeleteForAll:c}=a,r=Object(o.f)(e,s);r&&Object(j.a)("deleteHistory",{chat:r,shouldDeleteForAll:c,maxId:n})}),Object(s.b)("markMessageListRead",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:n,threadId:c}=s,r=Object(o.Ab)(e,n,c);if(!r)return;const{maxId:i}=a;Object(j.a)("markMessageListRead",{chat:r,threadId:c,maxId:i})}),Object(s.b)("markMessagesRead",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageIds:n}=a;Object(j.a)("markMessagesRead",{chat:s,messageIds:n})}),Object(s.b)("loadWebPagePreview",(e,t,a)=>{const{text:n}=a;!async function(e){const t=await Object(j.a)("fetchWebPagePreview",{message:e});Object(s.g)({...Object(s.e)(),webPagePreview:t})}(n)}),Object(s.b)("clearWebPagePreview",e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}}),Object(s.b)("sendPollVote",(e,t,a)=>{const{chatId:s,messageId:n,options:c}=a,r=Object(o.f)(e,s);r&&Object(j.a)("sendPollVote",{chat:r,messageId:n,options:c})}),Object(s.b)("loadPollOptionResults",(e,t,a)=>{const{chat:n,messageId:c,option:o,offset:i,limit:l,shouldResetVoters:b}=a;!async function(e,t,a,n,c,o){const i=await Object(j.a)("loadPollOptionResults",{chat:e,messageId:t,option:a,offset:n,limit:c});if(!i)return;let l=Object(s.e)();l=Object(r.e)(l,Object(d.c)(i.users,"id"));const{voters:b}=l.pollResults;Object(s.g)({...l,pollResults:{...l.pollResults,voters:{...b,[a]:[...!o&&b&&b[a]?b[a]:[],...i&&i.users.map(e=>e.id)].filter((e,t,a)=>a.indexOf(e)===t)},offsets:{...l.pollResults.offsets?l.pollResults.offsets:{},[a]:i.nextOffset||""}}})}(n,c,o,i,l,b)}),Object(s.b)("forwardMessages",e=>{const{fromChatId:t,messageIds:a,toChatId:n}=e.forwardMessages,c=t?Object(o.f)(e,t):void 0,r=n?Object(o.f)(e,n):void 0,i=t&&a?a.sort((e,t)=>e-t).map(a=>Object(o.k)(e,t,a)).filter(Boolean):void 0;c&&r&&i&&i.length&&function(e,t,a){Object(j.a)("forwardMessages",{fromChat:e,toChat:t,messages:a}),Object(s.g)({...Object(s.e)(),forwardMessages:{}})}(c,r,i)}),Object(s.b)("loadScheduledHistory",e=>{const t=Object(o.r)(e);if(!t)return;const{hash:a}=e.scheduledMessages.byChatId[t.id]||{};!async function(e,t){const a=await Object(j.a)("fetchScheduledHistory",{chat:e,hash:t});if(!a)return;const{hash:n,messages:c}=a,o=Object(d.c)(c,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.t)(b,e.id,o,n),b=Object(r.v)(b,e.id,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(b)}(t,a)}),Object(s.b)("sendScheduledMessages",(e,t,a)=>{const{chatId:s,id:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("sendScheduledMessages",{chat:c,ids:[n]})}),Object(s.b)("rescheduleMessage",(e,t,a)=>{const{chatId:s,messageId:n,scheduledAt:c}=a,r=Object(o.f)(e,s),i=r&&Object(o.mb)(e,r.id,n);r&&i&&Object(j.a)("rescheduleMessage",{chat:r,message:i,scheduledAt:c})}),Object(s.b)("requestThreadInfoUpdate",(e,t,a)=>{const{chatId:s,threadId:n}=a,c=Object(o.Ab)(e,s,n);c&&Object(j.a)("requestThreadInfoUpdate",{chat:c,threadId:n})}),Object(s.b)("loadPinnedMessages",(e,t,a)=>{const{chatId:n}=a,c=Object(o.f)(e,n);c&&async function(e){const t=await Object(j.a)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:a,chats:n,users:c}=t,o=Object(d.c)(a,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.b)(b,e.id,o),b=Object(r.v)(b,e.id,i.MAIN_THREAD_ID,"pinnedIds",l),b=Object(r.e)(b,Object(d.c)(c,"id")),b=Object(r.c)(b,Object(d.c)(n,"id")),Object(s.g)(b)}(c)}),Object(s.b)("loadMessageLink",(e,t,a)=>{const{messageId:s,chatId:n}=a,c=Object(o.f)(e,n),r=Object(o.k)(e,n,s);c&&r&&(async()=>{const e=await Object(j.a)("fetchMessageLink",{chat:c,message:r});e&&Object(w.c)(e.link)})()});var N=a(46);const P=Object(g.g)(e=>e(),500,!1);async function T(e,t){const a=await Object(j.a)("searchGifs",{query:e,offset:t});a&&Object(s.g)(Object(r.O)(Object(s.e)(),!t,a.gifs,a.nextOffset))}Object(s.b)("loadStickerSets",e=>{const{hash:t}=e.stickers.added||{};!async function(e=0){const t=await Object(j.a)("fetchStickerSets",{hash:e});if(!t)return;Object(s.g)(Object(r.gb)(Object(s.e)(),"added",t.hash,t.sets))}(t)}),Object(s.b)("loadAddedStickers",(e,t)=>{const{setIds:a}=e.stickers.added;a&&a.length&&(async()=>{for(let e=0;e0&&await Object(g.e)(500)})()}),Object(s.b)("loadRecentStickers",e=>{const{hash:t}=e.stickers.recent||{};!async function(e=0){const t=await Object(j.a)("fetchRecentStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,recent:t}})}(t)}),Object(s.b)("loadFavoriteStickers",e=>{const{hash:t}=e.stickers.favorite||{};!async function(e=0){const t=await Object(j.a)("fetchFavoriteStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,favorite:t}})}(t)}),Object(s.b)("loadFeaturedStickers",e=>{const{hash:t}=e.stickers.featured||{};!async function(e=0){const t=await Object(j.a)("fetchFeaturedStickers",{hash:e});if(!t)return;Object(s.g)(Object(r.gb)(Object(s.e)(),"featured",t.hash,t.sets))}(t)}),Object(s.b)("loadStickers",(e,t,a)=>{const{stickerSetId:n}=a;let{stickerSetAccessHash:c}=a;if(!c){const t=Object(o.ub)(e,n);if(!t)return;c=t.accessHash}!async function(e,t){const a=await Object(j.a)("fetchStickers",{stickerSetId:e,accessHash:t});if(!a)return;const{set:n,stickers:c,packs:o}=a;let i=Object(s.e)();i=Object(r.fb)(i,n.id,{...n,stickers:c,packs:o});const l=i.stickers.forEmoji.emoji;l&&o[l]&&(i=Object(r.n)(i));Object(s.g)(i)}(n,c)}),Object(s.b)("loadAnimatedEmojis",()=>{!async function(){const e=await Object(j.a)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:a}=e;Object(s.g)(Object(r.p)(Object(s.e)(),{...t,stickers:a}))}()}),Object(s.b)("loadSavedGifs",e=>{const{hash:t}=e.gifs.saved;!async function(e=0){const t=await Object(j.a)("fetchSavedGifs",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,gifs:{...a.gifs,saved:t}})}(t)}),Object(s.b)("faveSticker",(e,t,a)=>{const{sticker:s}=a;s&&Object(j.a)("faveSticker",{sticker:s})}),Object(s.b)("unfaveSticker",(e,t,a)=>{const{sticker:n}=a;n&&function(e){const t=Object(s.e)();Object(s.g)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter(({id:t})=>t!==e.id)}}}),Object(j.a)("faveSticker",{sticker:e,unfave:!0})}(n)}),Object(s.b)("toggleStickerSet",(e,t,a)=>{const{stickerSetId:s}=a,n=Object(o.ub)(e,s);if(!n)return;const{accessHash:c,installedDate:r}=n;Object(j.a)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:s,accessHash:c})}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:n}=a;n&&P(()=>{!async function(e,t=0){const a=await Object(j.a)("searchStickers",{query:e,hash:t});if(!a)return;const n=Object(s.e)(),{setsById:c,added:o}=n.stickers,i=a.sets.map(({id:e})=>e);o.setIds&&o.setIds.forEach(t=>{if(!i.includes(t)){const{title:a}=c[t]||{};a&&Object(N.a)(a,e)&&i.unshift(t)}});Object(s.g)(Object(r.gb)(n,"search",a.hash,a.sets,i))}(n)})}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;"string"==typeof s&&P(()=>{T(s)})}),Object(s.b)("searchMoreGifs",e=>{const{query:t,offset:a}=e.gifs.search;"string"==typeof t&&P(()=>{T(t,a)})}),Object(s.b)("loadStickersForEmoji",(e,t,a)=>{const{emoji:n}=a,{hash:c}=e.stickers.forEmoji;P(()=>{!async function(e,t=0){let a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,forEmoji:{...a.stickers.forEmoji,emoji:e}}});const n=await Object(j.a)("fetchStickersForEmoji",{emoji:e,hash:t});if(a=Object(s.e)(),!n||a.stickers.forEmoji.emoji!==e)return;a=Object(r.hb)(a,e,n.stickers,n.hash),Object(s.g)(a)}(n,c)})}),Object(s.b)("clearStickersForEmoji",e=>({...e,stickers:{...e.stickers,forEmoji:{}}}));var A=a(30);const x=Object(g.g)(e=>e(),500,!1);async function R(e="",t,a,c,i,l){let b;if(c){const s=await Object(j.a)("searchMessagesLocal",{chatOrUser:c,query:e,type:t,limit:n.x,offsetId:a,minDate:l,maxDate:i});if(s){const{messages:e,users:t,totalCount:a,nextOffsetId:n}=s;b={messages:e,users:t,chats:[],totalCount:a,nextRate:n}}}else b=await Object(j.a)("searchMessagesGlobal",{query:e,offsetRate:a,limit:n.x,type:t,maxDate:i,minDate:l});let u=Object(s.e)();const m=Object(o.t)(u);if(!b||""!==e&&e!==m)return void Object(s.g)(Object(r.R)(u,{messages:!1}));const{messages:h,users:O,chats:g,totalCount:f,nextRate:p}=b;g.length&&(u=Object(r.c)(u,Object(d.c)(g,"id"))),O.length&&(u=Object(r.e)(u,Object(d.c)(O,"id"))),h.length&&(u=Object(r.d)(u,h)),u=Object(r.S)(u,h,f,t,p),Object(s.g)(u)}Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{chatId:n}=e.globalSearch,{query:c}=a;c&&!n&&x(()=>{!async function(e){const t=await Object(j.a)("searchChats",{query:e});let a=Object(s.e)();const n=Object(o.t)(a);if(!t||!n||e!==n)return void Object(s.g)(Object(r.R)(a,{chats:!1}));const{localChats:c,localUsers:i,globalChats:l,globalUsers:b}=t;(c.length||l.length)&&(a=Object(r.c)(a,Object(d.c)([...c,...l],"id")));(i.length||b.length)&&(a=Object(r.e)(a,Object(d.c)([...i,...b],"id")));a=Object(r.R)(a,{chats:!1}),a=Object(r.P)(a,{localResults:{chatIds:c.map(({id:e})=>e),userIds:i.map(({id:e})=>e)},globalResults:{...a.globalSearch.globalResults,chatIds:b.map(({id:e})=>e),userIds:l.map(({id:e})=>e)}}),Object(s.g)(a)}(c)})}),Object(s.b)("setGlobalSearchDate",(e,t,a)=>{const{date:n}=a,c=n?Object(A.m)(n):n,i=Object(r.P)(e,{date:n,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});Object(s.g)(i);const{chatId:l}=e.globalSearch;R("","text",void 0,l?Object(o.f)(e,l):void 0,c,n)}),Object(s.b)("searchMessagesGlobal",(e,t,a)=>{const{query:s,resultsByType:n,chatId:c,date:r}=e.globalSearch,i=r?Object(A.m)(r):r,{type:l}=a,{nextOffsetId:d}=n&&n[l]||{};R(s,l,d,c?Object(o.f)(e,c):void 0,i,r)}),Object(s.b)("searchTextMessagesLocal",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},c=t?Object(o.f)(e,t):void 0,l=Object(o.A)(e);if(!c||!l||!a)return;const{query:b,results:u}=l,m=u?u.nextOffsetId:void 0;let h;if(a!==i.MAIN_THREAD_ID){const s=Object(o.zb)(e,t,a);h=s?s.topMessageId:void 0}!async function(e,t,a,c,i){const l=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:"text",query:c,topMessageId:a,limit:n.W,offsetId:i});if(!l)return;const{messages:b,users:u,totalCount:m,nextOffsetId:h}=l,O=Object(d.c)(b,"id"),g=Object.keys(O).map(Number);let f=Object(s.e)();const p=Object(o.A)(f);if(!p||c&&c!==p.query)return;f=Object(r.b)(f,e.id,O),f=Object(r.e)(f,Object(d.c)(u,"id")),f=Object(r.X)(f,e.id,t,g,m,h),Object(s.g)(f)}(c,a,h,b,m)}),Object(s.b)("searchMediaMessagesLocal",e=>{const t=Object(o.w)(e),a=t?e.users.byId[t]||e.chats.byId[t]:void 0,c=Object(o.v)(e);if(!a||!c)return;const{currentType:i,resultsByType:l}=c,b=i&&l&&l[i],u=b?b.nextOffsetId:void 0;i&&async function(e,t,a){const c=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:t,limit:n.mb,offsetId:a});if(!c)return;const{messages:i,users:l,totalCount:b,nextOffsetId:u}=c,m=Object(d.c)(i,"id"),h=Object.keys(m).map(Number);let O=Object(s.e)();if(!Object(o.v)(O))return;O=Object(r.b)(O,e.id,m),O=Object(r.e)(O,Object(d.c)(l,"id")),O=Object(r.U)(O,e.id,t,h,b,u),Object(s.g)(O)}(a,i,u)}),Object(s.b)("searchMessagesByDate",(e,t,a)=>{const{timestamp:n}=a,{chatId:c}=Object(o.y)(e)||{};if(!c)return;const r=Object(o.f)(e,c);r&&async function(e,t){const a=await Object(j.a)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});if(!a)return;Object(s.d)().focusMessage({chatId:e.id,messageId:a})}(r,n)}),Object(s.b)("checkPublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};if(!n)return;if(e.management.progress===l.f.InProgress)return;const{username:c}=a;(async()=>{e=Object(r.Z)(e,l.f.InProgress),e=Object(r.Y)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e);const t=await Object(j.a)("checkChatUsername",{username:c});e=Object(s.e)(),e=Object(r.Z)(e,t?l.f.Complete:l.f.Error),e=Object(r.Y)(e,n,{isUsernameAvailable:t}),Object(s.g)(e)})()}),Object(s.b)("updatePublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};let c=n&&Object(o.f)(e,n);if(!n||!c)return;const{username:i}=a;(async()=>{if(e=Object(r.Z)(e,l.f.InProgress),Object(s.g)(e),Object(m.hb)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}const a=await Object(j.a)("setChatUsername",{chat:c,username:i});e=Object(s.e)(),e=Object(r.Z)(e,a?l.f.Complete:l.f.Error),e=Object(r.Y)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e)})()}),Object(s.b)("updatePrivateLink",e=>{const{chatId:t}=Object(o.y)(e)||{},a=t&&Object(o.f)(e,t);t&&a&&Object(j.a)("updatePrivateLink",{chat:a})});var L=a(32);async function F(){const e=await Object(j.a)("fetchChats",{limit:n.i,archived:!0,withPinned:!0});if(!e)return;let t=Object(s.e)();t=Object(r.mb)(t,Object(d.c)(e.users,"id")),t=Object(r.K)(t,Object(d.c)(e.chats,"id")),t=Object(r.q)(t,"archived",e.chatIds),t=Object(r.H)(t,"archived",e),Object(s.g)(t)}async function D(){let e=Object(s.e)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:a}=e.contactList||{};if(!(a&&a.length||t&&t.length))return;const n=[...t||[],...a||[]].map(t=>Object(o.Db)(e,t)).filter(Boolean),c=await Object(j.a)("fetchUsers",{users:n});c&&(e=Object(s.e)(),e=Object(r.mb)(e,Object(d.c)(c,"id")),Object(s.g)(e))}Object(s.b)("sync",(e,t)=>{!async function(e){n.o&&console.log(">>> START SYNC");Object(L.a)(),await Object(j.a)("fetchCurrentUser");const t=await async function(){const e=await Object(j.a)("fetchChats",{limit:n.i,withPinned:!0});if(!e)return;let t=Object(s.e)();const{recentlyFoundChatIds:a}=t.globalSearch,{userIds:c}=t.contactList||{},{currentUserId:l}=t,b=[...a||[],...c||[],...l?[l]:[]],u=b.map(e=>Object(o.Db)(t,e)).filter(Boolean),h=b.map(e=>Object(o.f)(t,e)).filter(Boolean),{chatId:O}=Object(o.y)(t)||{};if(O){const e=Object(o.f)(t,O);if(e&&!b.includes(O)&&h.push(e),Object(m.kb)(O)){const e=Object(o.Db)(t,O);e&&!b.includes(O)&&u.push(e)}}u.push(...e.users),h.push(...e.chats),t=Object(r.r)(t,Object(d.c)(h,"id")),t=Object(r.q)(t,"active",e.chatIds),t={...t,chats:{...t.chats}},t=Object(r.H)(t,"active",e),Object.keys(e.draftsById).map(Number).forEach(a=>{t=Object(r.v)(t,a,i.MAIN_THREAD_ID,"draft",e.draftsById[a])}),Object.keys(e.replyingToById).map(Number).forEach(a=>{t=Object(r.v)(t,a,i.MAIN_THREAD_ID,"replyingToId",e.replyingToById[a])}),Object(s.g)(t),O&&!t.chats.byId[O]&&Object(s.d)().openChat({id:void 0});return u}();await async function(e){let t=!1,a=e||[],c=Object(s.e)();const{chatId:l}=Object(o.y)(c)||{},b=Object.keys(c.messages.byChatId).map(Number).reduce((e,t)=>{const a=Object(o.B)(c,t,i.MAIN_THREAD_ID);return a?{...e,[t]:a}:e},{});if(l){const e=await(u=c.chats.byId[l],Object(j.a)("fetchMessages",{chat:u,threadId:i.MAIN_THREAD_ID,offsetId:u.lastReadInboxMessageId,addOffset:-(Math.round(n.U/2)+1),limit:n.U}));c=Object(s.e)();const{chatId:b}=Object(o.y)(c)||{};if(e&&b===l){const s=c.messages.byChatId[l],n=Object(d.c)(e.messages,"id"),o=Object.keys(n).map(Number);c={...c,messages:{...c.messages,byChatId:{[l]:{byId:n,threadsById:{[i.MAIN_THREAD_ID]:{...s&&s.threadsById[i.MAIN_THREAD_ID],listedIds:o,viewportIds:o,outlyingIds:void 0}}}}}},c=Object(r.K)(c,Object(d.c)(e.chats,"id")),c=Object(r.jb)(c,l,e.threadInfos),t=!0,a=Array.prototype.concat(a,e.users)}}var u;t||(c={...c,messages:{...c.messages,byChatId:{}}});Object.keys(b).map(Number).forEach(e=>{c=Object(r.v)(c,e,i.MAIN_THREAD_ID,"draft",b[e])}),e?c=Object(r.w)(c,Object(d.c)(a,"id")):a&&(c=Object(r.mb)(c,Object(d.c)(a,"id")));Object(s.g)(c)}(t),Object(s.g)({...Object(s.e)(),lastSyncTime:Date.now()}),n.o&&console.log(">>> FINISH SYNC");e()}(t.afterSync)}),Object(s.b)("afterSync",(e,t)=>{!async function(e){n.o&&console.log(">>> START AFTER-SYNC");e.loadFavoriteStickers(),await Promise.all([D(),F()]),await Object(j.a)("fetchCurrentUser"),n.o&&console.log(">>> FINISH AFTER-SYNC")}(t)});const B=Object(g.a)(e=>e(),500,!1,!0);function U(e,{visibility:t,allowedIds:a,deniedIds:s}){const{users:{byId:n},chats:{byId:c}}=e,r={visibility:t};let o,i;const l=e=>{if(!Object(m.kb)(e))return;const{id:t,accessHash:a}=n[e]||{};return t?{id:t,accessHash:a}:void 0},d=e=>{if(Object(m.kb)(e))return;const t=c[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(o=a.map(l).filter(Boolean),i=a.map(d).filter(Boolean),o.length>0&&(r.allowedUsers=o),i.length>0&&(r.allowedChats=i)),"everybody"!==t&&"contacts"!==t||(o=s.map(l).filter(Boolean),i=s.map(d).filter(Boolean),o.length>0&&(r.blockedUsers=o),i.length>0&&(r.blockedChats=i)),r}Object(s.b)("loadFullUser",(e,t,a)=>{const{userId:s}=a,n=Object(o.Db)(e,s);if(!n)return;const{id:c,accessHash:r}=n;B(()=>Object(j.a)("fetchFullUser",{id:c,accessHash:r}))}),Object(s.b)("loadUser",(e,t,a)=>{const{userId:n}=a,c=Object(o.Db)(e,n);c&&(async()=>{const t=await Object(j.a)("fetchUsers",{users:[c]});t&&(e=Object(s.e)(),e=Object(r.mb)(e,Object(d.c)(t,"id")),Object(s.g)(e))})()}),Object(s.b)("loadTopUsers",e=>{const{hash:t,lastRequestedAt:a}=e.topPeers;(!a||Date.now()-a>6e4)&&async function(e){const t=await Object(j.a)("fetchTopUsers",{hash:e});if(!t)return;const{hash:a,ids:n,users:c}=t;let o=Object(s.e)();o=Object(r.e)(o,Object(d.c)(c,"id")),o={...o,topPeers:{...o.topPeers,hash:a,userIds:n,lastRequestedAt:Date.now()}},Object(s.g)(o)}(t)}),Object(s.b)("loadContactList",e=>{const{hash:t}=e.contactList||{};!async function(e){const t=await Object(j.a)("fetchContactList",{hash:e});if(!t)return;let a=Object(r.e)(Object(s.e)(),Object(d.c)(t.users,"id"));a=Object(r.c)(a,Object(d.c)(t.chats,"id"));const n=e=>e.lastName||e.firstName||"",c=new Intl.Collator("en-US"),o=t.users.sort((e,t)=>c.compare(n(e),n(t))).filter(e=>!e.isSelf);Object(s.g)({...a,contactList:{hash:t.hash,userIds:o.map(e=>e.id)}})}(t)}),Object(s.b)("loadCurrentUser",()=>{Object(j.a)("fetchCurrentUser")}),Object(s.b)("updateContact",(e,t,a)=>{const{userId:n,isMuted:c,firstName:i,lastName:d}=a;!async function(e,t,a,n){const c=Object(s.e)(),i=Object(o.Db)(c,e);if(!i)return;Object(s.d)().updateChatMutedState({chatId:e,isMuted:t}),Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.InProgress));await Object(j.a)("updateContact",{phone:i.phoneNumber,firstName:a,lastName:n})&&Object(s.g)(Object(r.lb)(Object(s.e)(),i.id,{firstName:a,lastName:n}));Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.Complete))}(n,c,i,d)}),Object(s.b)("deleteUser",(e,t,a)=>{const{userId:n}=a;!async function(e){const t=Object(s.e)(),a=Object(o.Db)(t,e);if(!a)return;const{id:n,accessHash:c}=a;await Object(j.a)("deleteUser",{id:n,accessHash:c})}(n)}),Object(s.b)("loadProfilePhotos",(e,t,a)=>{const{profileId:n}=a,c=Object(m.kb)(n),i=c?Object(o.Db)(e,n):void 0,l=c?void 0:Object(o.f)(e,n);(async()=>{const e=await Object(j.a)("fetchProfilePhotos",i,l);if(!e||!e.photos)return;let t=Object(s.e)();c?t=Object(r.lb)(t,n,{photos:e.photos}):(t=Object(r.e)(t,Object(d.c)(e.users,"id")),t=Object(r.F)(t,n,{photos:e.photos})),Object(s.g)(t)})()}),Object(s.b)("clickInlineButton",(e,t,a)=>{const{button:c}=a;switch(c.type){case"command":t.sendBotCommand({command:c.value});break;case"url":c.value.match(n.gb)||c.value.match(n.hb)?t.openTelegramLink({url:c.value}):window.open(c.value);break;case"callback":{const t=Object(o.r)(e);if(!t)return;!async function(e,t,a){const n=await Object(j.a)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:a});if(!n||!n.message)return;const{message:c,alert:r}=n;r?Object(s.d)().showError({error:{message:c}}):Object(s.d)().showNotification({message:c})}(t,c.messageId,c.value);break}case"requestPoll":t.openPollModal();break;case"buy":{const a=Object(o.r)(e),{messageId:s,value:n}=c;if(!a)return;n?t.getReceipt({receiptMessageId:n,chatId:a.id,messageId:s}):(t.getPaymentForm({messageId:s}),t.setInvoiceMessageInfo(Object(o.k)(e,a.id,s)),t.openPaymentModal({messageId:s}));break}}}),Object(s.b)("sendBotCommand",(e,t,a)=>{const{command:s}=a,{currentUserId:n}=e,c=Object(o.r)(e);n&&c&&async function(e,t,a){await Object(j.a)("sendMessage",{chat:e,text:a})}(c,0,s)}),Object(s.b)("updateProfile",(e,t,a)=>{const{photo:n,firstName:c,lastName:i,bio:d,username:b}=a;(async()=>{const{currentUserId:t}=e;if(t){if(Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.InProgress}}),n&&await Object(j.a)("updateProfilePhoto",n),c||i||d){if(await Object(j.a)("updateProfile",{firstName:c,lastName:i,about:d})){e=Object(s.e)();const a=t&&Object(o.Db)(e,t);a&&Object(s.g)(Object(r.lb)(e,a.id,{firstName:c,lastName:i,fullInfo:{...a.fullInfo,bio:d}}))}}if(b){await Object(j.a)("updateUsername",b)&&t&&Object(s.g)(Object(r.lb)(Object(s.e)(),t,{username:b}))}Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.Complete}})}})()}),Object(s.b)("checkUsername",(e,t,a)=>{const{username:n}=a;(async()=>{if(e.profileEdit&&e.profileEdit.progress===l.j.InProgress)return;Object(s.g)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:l.j.Idle,isUsernameAvailable:void 0}});const t=await Object(j.a)("checkUsername",n);e=Object(s.e)(),Object(s.g)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()}),Object(s.b)("loadWallpapers",()=>{(async()=>{const e=await Object(j.a)("fetchWallpapers",0);if(!e)return;const t=Object(s.e)();Object(s.g)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()}),Object(s.b)("uploadWallpaper",(e,t,a)=>{const n=a,c=URL.createObjectURL(n);Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[{slug:l.n,document:{fileName:"",size:n.size,mimeType:n.type,previewBlobUrl:c}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await Object(j.a)("uploadWallpaper",n);if(!t)return;const{wallpaper:a}=t;if(!(e=Object(s.e)()).settings.loadedWallpapers)return;const r=e.settings.loadedWallpapers[0];if(!r||r.slug!==l.n)return;const o={...a,document:{...a.document,previewBlobUrl:c}};Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[o,...e.settings.loadedWallpapers.slice(1)]}})})()}),Object(s.b)("loadBlockedContacts",()=>{(async()=>{const e=await Object(j.a)("fetchBlockedContacts");if(!e)return;let t=Object(s.e)();e.users&&e.users.length&&(t=Object(r.e)(t,Object(d.c)(e.users,"id"))),e.chats&&e.chats.length&&(t=Object(r.K)(t,Object(d.c)(e.chats,"id"))),t={...t,blocked:{...t.blocked,ids:[...t.blocked.ids||[],...e.blockedIds],totalCount:e.totalCount}},Object(s.g)(t)})()}),Object(s.b)("blockContact",(e,t,a)=>{const{contactId:n}=a;(async()=>{if(!await Object(j.a)("blockContact",n))return;const e=Object(s.e)();Object(s.g)(Object(r.a)(e,n))})()}),Object(s.b)("unblockContact",(e,t,a)=>{const{contactId:n}=a;let c;if(Object(m.kb)(n)){const t=Object(o.Db)(e,n);if(!t)return;c=t.accessHash}(async()=>{if(!await Object(j.a)("unblockContact",n,c))return;const e=Object(s.e)();Object(s.g)(Object(r.o)(e,n))})()}),Object(s.b)("loadAuthorizations",()=>{(async()=>{const e=await Object(j.a)("fetchAuthorizations");e&&Object(s.g)({...Object(s.e)(),activeSessions:e})})()}),Object(s.b)("terminateAuthorization",(e,t,a)=>{const{hash:n}=a;(async()=>{if(!await Object(j.a)("terminateAuthorization",n))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.hash!==n)})})()}),Object(s.b)("terminateAllAuthorizations",()=>{(async()=>{if(!await Object(j.a)("terminateAllAuthorizations"))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.isCurrent)})})()}),Object(s.b)("loadNotificationsSettings",()=>{(async()=>{const e=await Object(j.a)("loadNotificationsSettings");e&&Object(s.g)(Object(r.u)(Object(s.e)(),e))})()}),Object(s.b)("updateNotificationSettings",(e,t,a)=>{const{peerType:n,isSilent:c,isShowPreviews:o}=a;(async()=>{await Object(j.a)("updateNotificationSettings",n,{isSilent:c,isShowPreviews:o})&&Object(s.g)(Object(r.ab)(Object(s.e)(),n,c,o))})()}),Object(s.b)("updateContactSignUpNotification",(e,t,a)=>{const{isSilent:n}=a;(async()=>{await Object(j.a)("updateContactSignUpNotification",n)&&Object(s.g)(Object(r.u)(Object(s.e)(),{hasContactJoinedNotifications:!n}))})()}),Object(s.b)("loadLanguages",()=>{(async()=>{const e=await Object(j.a)("fetchLanguages");e&&Object(s.g)(Object(r.u)(Object(s.e)(),{languages:e}))})()}),Object(s.b)("loadPrivacySettings",()=>{(async()=>{const[e,t,a,n,c]=await Promise.all([Object(j.a)("fetchPrivacySettings","phoneNumber"),Object(j.a)("fetchPrivacySettings","lastSeen"),Object(j.a)("fetchPrivacySettings","profilePhoto"),Object(j.a)("fetchPrivacySettings","forwards"),Object(j.a)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&a&&n&&c))return;const r=Object(s.e)();r.settings.privacy.phoneNumber=e,r.settings.privacy.lastSeen=t,r.settings.privacy.profilePhoto=a,r.settings.privacy.forwards=n,r.settings.privacy.chatInvite=c,Object(s.g)(r)})()}),Object(s.b)("setPrivacyVisibility",(e,t,a)=>{const{privacyKey:n,visibility:c}=a,{privacy:{[n]:r}}=e.settings;if(!r)return;const o=U(e,{visibility:c,allowedIds:[...r.allowUserIds,...r.allowChatIds],deniedIds:[...r.blockUserIds,...r.blockChatIds]});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,o);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("setPrivacySettings",(e,t,a)=>{const{privacyKey:n,isAllowList:c,contactsIds:r}=a,{privacy:{[n]:o}}=e.settings;if(!o)return;const i=U(e,{visibility:o.visibility,allowedIds:c?r:[...o.allowUserIds,...o.allowChatIds],deniedIds:c?[...o.blockUserIds,...o.blockChatIds]:r});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,i);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("loadPasswordInfo",()=>{(async()=>{const e=await Object(j.a)("getPasswordInfo");if(!e)return;let t=Object(s.e)();t=Object(r.u)(t,{hasPassword:e.hasPassword}),t=Object(r.kb)(t,{hint:e.hint}),Object(s.g)(t)})()}),Object(s.b)("checkPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("checkPassword",n);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("clearPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("clearPassword",n);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("updatePassword",(e,t,a)=>{const{currentPassword:n,password:c,hint:o,email:i,onSuccess:l}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updatePassword",n,c,o,i);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&l()})()}),Object(s.b)("updateRecoveryEmail",(e,t,a)=>{const{currentPassword:n,email:c,onSuccess:o}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updateRecoveryEmail",n,c);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&o()})()}),Object(s.b)("provideTwoFaEmailCode",(e,t,a)=>{const{code:s}=a;Object(j.a)("provideRecoveryEmailCode",s)}),Object(s.b)("clearTwoFaError",e=>Object(r.kb)(e,{error:void 0}));var H=a(54);Object(s.b)("validateRequestedInfo",(e,t,a)=>{const{requestInfo:n,saveInfo:c}=a,i=Object(o.eb)(e);i&&async function(e,t,a){const n=await Object(j.a)("validateRequestedInfo",{messageId:e,requestInfo:t,shouldSave:a});if(!n)return;const{id:c,shippingOptions:o}=n;if(!c)return;let i=Object(r.C)(Object(s.e)(),c);o?(i=Object(r.eb)(i,o),i=Object(r.A)(i,l.i.Shipping)):i=Object(r.A)(i,l.i.PaymentInfo);Object(s.g)(i)}(i,n,c)}),Object(s.b)("getPaymentForm",(e,t,a)=>{const{messageId:n}=a;n&&async function(e){const t=await Object(j.a)("getPaymentForm",{messageId:e});if(!t)return;let a=Object(r.z)(Object(s.e)(),t),n=l.i.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(n=l.i.ShippingInfo);a=Object(r.A)(a,n),Object(s.g)(a)}(n)}),Object(s.b)("getReceipt",(e,t,a)=>{const{receiptMessageId:n,chatId:c,messageId:i}=a;i&&n&&c&&async function(e,t,a){const n=await Object(j.a)("getReceipt",t);if(!n)return;let c=Object(s.e)();const i=Object(o.k)(c,a,e);c=Object(r.B)(c,n,i),Object(s.g)(c)}(i,n,c)}),Object(s.b)("clearPaymentError",e=>{Object(s.g)({...e,payment:{...e.payment,error:void 0}})}),Object(s.b)("clearReceipt",e=>{Object(s.g)({...e,payment:{...e.payment,receipt:void 0}})}),Object(s.b)("sendCredentialsInfo",(e,t,a)=>{const n=Object(o.hb)(e);if(!n)return;const{credentials:c}=a,{data:i}=c;!async function(e,t){const a=function(e){const t=Object.keys(e).map(t=>`${t}=${e[t]}`).join("&");return t.length>0?"?"+t:""}({"card[number]":e.cardNumber,"card[exp_month]":e.expiryMonth,"card[exp_year]":e.expiryYear,"card[cvc]":e.cvv,"card[address_zip]":e.zip,"card[address_country]":e.country}),n=await fetch("https://api.stripe.com/v1/tokens"+a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:"Bearer "+t}}),c=await n.json();if(c.error){const e=Object(H.b)(c.error),t=Object(s.e)();return void Object(s.g)({...t,payment:{...t.payment,error:{...e}}})}let o=Object(r.D)(Object(s.e)(),{type:c.type,id:c.id});o=Object(r.A)(o,l.i.Checkout),Object(s.g)(o)}(i,n)}),Object(s.b)("sendPaymentForm",(e,t,a)=>{const{shippingOptionId:n,saveCredentials:c}=a,i=Object(o.eb)(e),l=Object(o.fb)(e),d=Object(o.hb)(e),b=Object(o.wb)(e);i&&d&&async function(e,t,a,n){if(await Object(j.a)("sendPaymentForm",{messageId:e,credentials:t,requestedInfoId:a,shippingOptionId:n})){const e=Object(r.g)(Object(s.e)());Object(s.g)(Object(r.h)(e))}}(i,{save:c,data:b},l,n)}),Object(s.b)("setPaymentStep",(e,t,a={})=>Object(r.A)(e,a.step||l.i.ShippingInfo)),Object(s.b)("setInvoiceMessageInfo",(e,t,a)=>Object(r.y)(e,a));a(76);Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateChat":Object(o.L)(e,a.id)||t.loadTopChats(),Object(s.g)(Object(r.F)(e,a.id,a.chat,a.newProfilePhoto));break;case"updateChatJoin":{const n=Object(o.j)(e,a.id);if(!n)break;e=Object(r.G)(e,n,[a.id]),e=Object(r.F)(e,a.id,{isNotJoined:!1}),Object(s.g)(e);const c=Object(o.f)(e,a.id);c&&t.requestChatUpdate({chatId:c.id});break}case"updateChatLeave":{const t=Object(o.j)(e,a.id);if(!t)break;const{[t]:n}=e.chats.listIds;n&&(e=Object(r.q)(e,t,n.filter(e=>e!==a.id))),e=Object(r.F)(e,a.id,{isNotJoined:!0}),Object(s.g)(e);break}case"updateChatInbox":Object(s.g)(Object(r.F)(e,a.id,a.chat));break;case"updateChatTypingStatus":{const{id:t,typingStatus:n}=a;Object(s.g)(Object(r.F)(e,t,{typingStatus:n})),setTimeout(()=>{const e=Object(s.e)(),a=Object(o.f)(e,t);a&&n&&a.typingStatus&&a.typingStatus.timestamp===n.timestamp&&Object(s.g)(Object(r.F)(e,t,{typingStatus:void 0}))},6e3);break}case"newMessage":{const{message:n}=a,{chatId:c}=Object(o.y)(e)||{};if(n.senderId===e.currentUserId&&!n.isFromScheduled)return;const i=Object(o.f)(e,a.chatId);if(!i)return;a.chatId===c?setTimeout(()=>{t.requestChatUpdate({chatId:a.chatId})},1e3):Object(s.g)(Object(r.F)(e,a.chatId,{unreadCount:i.unreadCount?i.unreadCount+1:1,...a.message.hasUnreadMention&&{unreadMentionsCount:i.unreadMentionsCount?i.unreadMentionsCount+1:1}}));break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:n}=a;if(!1!==n.hasUnreadMention)return;t.forEach(t=>{const s="channelId"in a?a.channelId:Object(o.p)(e,t),n=Object(o.f)(e,s);n&&n.unreadMentionsCount&&(e=Object(r.F)(e,s,{unreadMentionsCount:n.unreadMentionsCount-1}))}),Object(s.g)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=a,n=e.chats.byId[a.id];if(!n)return;Object(s.g)(Object(r.F)(e,a.id,{fullInfo:{...n.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:c}=a,r=c===n.g?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},Object(s.g)(e);break}case"updateChatPinned":{const{id:t,isPinned:c}=a,r=Object(o.j)(e,t);if(r){const{[r]:a}=e.chats.orderedPinnedIds;let s=a||[];if(c){if(!s.includes(t)){if("active"===r&&s.length>=n.J){const t=e.chats.listIds.active;s=s.filter(e=>t&&t.includes(e))}s=[t,...s]}}else s=s.filter(e=>e!==t);e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:s.length?s:void 0}}}}Object(s.g)(e);break}case"updateChatListType":{const{id:t,folderId:n}=a;Object(s.g)(Object(r.I)(e,t,n));break}case"updateChatFolder":{const{id:t,folder:n}=a,{byId:c,orderedIds:r}=e.chatFolders,o=n?{...c,[t]:n}:Object(d.l)(c,Object.keys(c).map(Number).filter(e=>e!==t)),i=n?r&&r.includes(t)?r:[...r||[],t]:r?r.filter(e=>e!==t):void 0;Object(s.g)({...e,chatFolders:{...e.chatFolders,byId:o,orderedIds:i}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{const t=e.chats.byId[a.id],{replacedMembers:n,addedMember:c,deletedMemberId:o}=a;if(!t)return;let i=!1,l=t.fullInfo&&t.fullInfo.members?[...t.fullInfo.members]:[];if(n)l=n,i=!0;else if(c)l.length&&l.some(e=>e.userId===c.userId)||(l.push(c),i=!0);else if(l.length&&o){const e=l.findIndex(e=>e.userId===o);e>-1&&(l.slice(e,1),i=!0)}if(i){const n=l.filter(({isOwner:e,isAdmin:t})=>e||t);Object(s.g)(Object(r.F)(e,a.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:n}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:n}=a,c=e.chats.byId[t];c&&c.photos&&Object(s.g)(Object(r.F)(e,t,{photos:c.photos.filter(e=>!n.includes(e.id))}));break}}});function q(e,t,a,s,n=!1){const c=n?Object(o.mb)(e,t,a):Object(o.k)(e,t,a);if(c&&s.content){const{photo:e,video:t,sticker:a,document:n}=Object(m.v)(c);e&&s.content.photo?(s.content.photo.blobUrl=e.blobUrl,s.content.photo.thumbnail=e.thumbnail):t&&s.content.video?s.content.video.blobUrl=t.blobUrl:a&&s.content.sticker?s.content.sticker.isPreloadedGlobally=a.isPreloadedGlobally:n&&s.content.document&&(s.content.document.previewBlobUrl=n.previewBlobUrl)}return n?Object(r.cb)(e,t,a,s):Object(r.J)(e,t,a,s)}function G(e,t){const{id:a,chatId:s}=t;e=Object(r.T)(e,s,i.MAIN_THREAD_ID,[a]),Object(o.W)(e,s,i.MAIN_THREAD_ID)&&(e=Object(r.f)(e,s,i.MAIN_THREAD_ID,a));const{threadInfo:n,firstMessageId:c}=Object(o.yb)(e,s,t)||{};return!c&&Object(m.rb)(t)||n&&(e=Object(r.T)(e,s,n.threadId,[a]),Object(o.W)(e,s,n.threadId)&&(e=Object(r.f)(e,s,n.threadId,a),c||(e=Object(r.v)(e,s,n.threadId,"firstMessageId",t.id)),n.lastMessageId||(e=Object(r.v)(e,s,n.threadId,"threadInfo",{...n,lastMessageId:t.id})))),e}function _(e,t,a,s=!1){const{chats:n}=e,c=n.byId[t]&&n.byId[t].lastMessage;if(c&&!s){if(!(c.id===a.id||c.id===a.previousLocalId||a.id>c.id))return e}return Object(r.F)(e,t,{lastMessage:a})}function z(e,t){const a=Object(o.m)(e,t),s=Object(o.X)(e,t,i.MAIN_THREAD_ID);if(!a||!s)return;let n=s.length;for(;n--;){const e=a[s[n]];if(!e.isDeleting)return e}}function W(e,t,a,n){if(e){t.forEach(t=>{const a=z(n=Object(r.J)(n,e,t,{isDeleting:!0}),e);a&&(n=_(n,e,a,!0))}),Object(s.g)(n),a.requestChatUpdate({chatId:e});const c=[];return t.forEach(t=>{const a=Object(o.k)(n,e,t);if(!a)return;const{threadInfo:s}=Object(o.yb)(n,e,a)||{};s&&c.push(s.threadId)}),Object(d.o)(c).forEach(t=>{a.requestThreadInfoUpdate({chatId:e,threadId:t})}),void setTimeout(()=>{Object(s.g)(Object(r.i)(Object(s.e)(),e,t))},350)}const c=[];t.forEach(e=>{const t=Object(o.p)(n,e);if(t){c.push(t);const a=z(n=Object(r.J)(n,t,e,{isDeleting:!0}),t);a&&(n=_(n,t,a,!0)),setTimeout(()=>{Object(s.g)(Object(r.i)(Object(s.e)(),t,[e]))},350)}}),Object(s.g)(n),Object(d.o)(c).forEach(e=>{a.requestChatUpdate({chatId:e})})}Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"newMessage":{const{chatId:n,id:c,message:i}=a;e=G(e=q(e,n,c,i),i),i.threadInfo&&(e=Object(r.ib)(e,i.threadInfo.chatId,i.threadInfo.threadId,i.threadInfo)),Object(s.g)(e);const l=Object(o.k)(e,n,c);if(Object(o.a)(e,n,i)){if(i.isOutgoing&&(!i.content||!i.content.action)){const a=Object(o.y)(e);a&&t.focusMessage({chatId:n,threadId:a.threadId,messageId:i.id,noHighlight:!0})}const{threadInfo:a}=Object(o.yb)(e,n,i)||{};a&&t.requestThreadInfoUpdate({chatId:n,threadId:a.threadId}),i.isOutgoing||setTimeout(()=>{Object(s.g)(_(Object(s.e)(),n,l))},350)}else Object(s.g)(_(Object(s.e)(),n,l));Object(o.L)(e,n)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:n,message:c}=a;e=q(e,t,n,c,!0);const l=Object(o.lb)(e,t)||[];e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",Object(d.o)([...l,n])),Object(s.g)(e);break}case"updateMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.k)(e,t,n))return;e=q(e,t,n,c);const i=Object(o.k)(e,t,n);c.threadInfo&&(e=Object(r.ib)(e,c.threadInfo.chatId,c.threadInfo.threadId,c.threadInfo)),e=_(e,t,i),Object(s.g)(e);break}case"updateScheduledMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.mb)(e,t,n))return;e=q(e,t,n,c,!0);const l=Object.keys(Object(o.nb)(e,t)||{}).map(Number).sort((e,t)=>t-e);e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(e);break}case"updateMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a;e=G(e,c);const i=Object(o.k)(e,t,n);e=Object(r.i)(e,t,[n]),c.isScheduled&&(e=Object(r.j)(e,t,[n])),e=Object(r.J)(e,t,c.id,{...i,...c,previousLocalId:n});const l=Object(o.k)(e,t,c.id);e=_(e,t,l),Object(s.g)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a,l=Object(o.lb)(e,t)||[];e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",[...l,c.id]);const d=Object(o.mb)(e,t,n);e=Object(r.j)(e,t,[n]),e=Object(r.cb)(e,t,c.id,{...d,...c,previousLocalId:n}),Object(s.g)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:n,messageIds:c}=a,l=Object(o.gb)(e,t)||[],d=n?[...l,...c]:l.filter(e=>!c.includes(e));Object(s.g)(Object(r.v)(e,t,i.MAIN_THREAD_ID,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:n,threadInfo:c}=a,i={...Object(o.zb)(e,t,n),...c};if(!i.threadId)return;e=Object(r.ib)(e,t,n,i),Object(s.g)(e);break}case"resetMessages":{const{id:n}=a,c=Object(o.m)(e,n);c&&!Object(m.kb)(n)&&(e=Object(r.i)(e,n,Object.keys(c).map(Number)),Object(s.g)(e),t.loadFullChat({chatId:n,force:!0}));break}case"deleteMessages":{const{ids:s,chatId:n}=a;W(n,s,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:n}=a;!function(e,t,a,n){if(!e)return;t.forEach(t=>{n=Object(r.cb)(n,e,t,{isDeleting:!0})}),Object(s.g)(n),setTimeout(()=>{n=Object(r.j)(Object(s.e)(),e,t);const a=Object(o.nb)(n,e);n=Object(r.v)(n,e,i.MAIN_THREAD_ID,"scheduledIds",Object.keys(a||{}).map(Number)),Object(s.g)(n)},350)}(n,t,0,e);break}case"deleteHistory":{const{chatId:s}=a;W(s,Object.keys(e.messages.byChatId[s].byId).map(Number),t,e);break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:n}=a;t.forEach(t=>{const a=Object(o.p)(e,t);a&&(e=Object(r.J)(e,a,t,n))}),Object(s.g)(e);break}case"updateChannelMessages":{const{channelId:t,ids:n,messageUpdate:c}=a;n.forEach(a=>{e=Object(r.J)(e,t,a,c)}),Object(s.g)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:n}=a,c=Object(o.l)(e,t);if(c&&c.content.poll){const t={...c.content.poll,...n},{results:a}=t.results||{};if(a&&!a.some(e=>e.isChosen)){const{results:e}=c.content.poll.results,s=e&&e.filter(e=>e.isChosen);s&&s.forEach(e=>{const s=a.findIndex(t=>t.option===e.option);s>=0&&(t.results.results[s].isChosen=!0)})}Object(s.g)(Object(r.J)(e,c.chatId,c.id,{content:{...c.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:n,options:c}=a,i=Object(o.l)(e,t);if(!i||!i.content.poll||!i.content.poll.results)break;const{poll:l}=i.content,{recentVoterIds:d,totalVoters:b,results:u}=l.results,m=d?[...d]:[],h=b?b+1:1,O=u?[...u]:[];m.push(n),c.forEach(t=>{const a=O.find(e=>e.option===t),s=O.findIndex(e=>e.option===t),c=a?{...a}:{option:t,votersCount:0};c.votersCount+=1,n===e.currentUserId&&(c.isChosen=!0),s?O[s]=c:O.push(c)}),Object(s.g)(Object(r.J)(e,i.chatId,i.id,{content:{...i.content,poll:{...l,results:{...l.results,recentVoterIds:m,totalVoters:h,results:O}}}}));break}}});const V=Object(g.g)((function(){let e=Object(s.e)();$.forEach(([t,a])=>{e=Object(r.lb)(e,t,{status:a})}),Object(s.g)(e),$=[]}),3e3,!0);let $=[];Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"deleteUser":return Object(r.k)(e,a.id);case"updateUser":return Object(r.lb)(e,a.id,a.user);case"updateUserStatus":return s=a.userId,n=a.status,$.push([s,n]),void V();case"updateUserFullInfo":{const{id:t,fullInfo:s}=a,n=e.users.byId[t];if(!n)return;return Object(r.lb)(e,t,{fullInfo:{...n.fullInfo,...s}})}}var s,n}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateStickerSet":return Object(r.fb)(e,a.id,a.stickerSet)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updatePeerBlocked":return a.isBlocked?Object(r.a)(Object(s.e)(),a.id):Object(r.o)(Object(s.e)(),a.id);case"updateResetContactList":Object(s.g)({...Object(s.e)(),contactList:{hash:0,userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[a.key]=a.rules}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateNotifySettings":return Object(r.ab)(e,a.peerType,a.isSilent,a.isShowPreviews)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:a.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:a.message}}}});var Q=a(43),K=a(8),Y=a(29),J=a(127),Z=a(42),X=a(100),ee=a(66),te=a(94),ae=a(56),se=a(34),ne=a(25),ce=a(144),re=a(129);a(186);var oe=Object(c.h)(({id:e,name:t,value:a,label:s,checked:n=!1,disabled:r,inactive:o,onChange:i,onCheck:l})=>{const d=Object(c.m)(e=>{i&&i(e),l&&l(e.currentTarget.checked)},[i,l]),b=Object(K.a)("Switcher",r&&"disabled",o&&"inactive");return c.a.createElement("label",{className:b,title:s},c.a.createElement("input",{type:"checkbox",id:e,name:t,value:a,checked:n,disabled:r,onChange:d}),c.a.createElement("span",{className:"widget"}))});a(187);const ie=[0,1,2];var le=Object(c.h)(Object(s.h)(e=>{const{query:t,fetchingStatus:a,chatId:s,date:n}=e.globalSearch,{currentUserId:c}=e,{byId:r}=e.chats,{theme:o,animationLevel:i}=e.settings.byKey;return{searchQuery:t,isLoading:!!a&&Boolean(a.chats||a.messages),currentUserId:c,chatsById:r,globalSearchChatId:s,searchDate:n,theme:o,animationLevel:i}},(e,t)=>Object(d.l)(t,["openChat","openTipsChat","setGlobalSearchDate","setGlobalSearchChatId","setSettingOption"]))(({content:e,contactsFilter:t,onSearchQuery:a,onSelectSettings:s,onSelectContacts:r,onSelectArchived:o,setGlobalSearchChatId:i,onReset:d,searchQuery:b,isLoading:u,currentUserId:O,globalSearchChatId:j,searchDate:g,theme:f,animationLevel:p,chatsById:I,openChat:v,openTipsChat:y,setGlobalSearchDate:C,setSettingOption:w})=>{const E=e===l.d.ChatList,M={date:void 0},S={id:void 0},k=Object(c.p)(()=>g?Object(A.a)(new Date(1e3*g)):void 0,[g]),N=Object(c.p)(()=>E&&I?Object.values(I).reduce((e,t)=>Object(m.gb)(t)&&t.unreadCount?e+1:e,0):0,[E,I]),P=Object(c.p)(()=>({onTrigger:e,isOpen:t})=>c.a.createElement(ne.a,{round:!0,ripple:E&&!h.f,size:"smaller",color:"translucent",className:t?"active":"",onClick:E?e:()=>d(),ariaLabel:E?"Open menu":"Return to chat list"},c.a.createElement("div",{className:Object(K.a)("animated-menu-icon",!E&&"state-back")})),[E,d]),T=Object(c.m)(()=>{b||a("")},[b,a]),x=Object(c.m)(()=>{v({id:O})},[O,v]),R=Object(c.m)(e=>{e.stopPropagation();const t="light"===f?"dark":"light",a="dark"===t;w({theme:t,customBackground:a?n.m:void 0,patternColor:a?n.n:n.s}),Object(ee.a)(t,p>0)},[p,w,f]),L=Object(c.m)(e=>{e.stopPropagation();const t=0===p?2:0;ie.forEach((e,a)=>{document.body.classList.toggle("animation-level-"+a,t===a)}),w({animationLevel:t})},[p,w]),F=Object(te.a)(),D=Boolean(j)||e===l.d.GlobalSearch||e===l.d.Contacts,B=e===l.d.Contacts?F("SearchFriends"):F("Search");return c.a.createElement("div",{className:"LeftMainHeader"},c.a.createElement("div",{id:"LeftMainHeader",className:"left-header"},c.a.createElement(ae.a,{trigger:P,footer:n.f},c.a.createElement(se.a,{icon:"saved-messages",onClick:x},F("SavedMessages")),c.a.createElement(se.a,{icon:"archive",onClick:o},c.a.createElement("span",{className:"menu-item-name"},F("ArchivedChats")),N>0&&c.a.createElement("div",{className:"archived-badge"},N)),c.a.createElement(se.a,{icon:"user",onClick:r},F("Contacts")),c.a.createElement(se.a,{icon:"settings",onClick:s},F("Settings")),c.a.createElement(se.a,{icon:"darkmode",onClick:R},c.a.createElement("span",{className:"menu-item-name"},"Dark Mode"),c.a.createElement(oe,{id:"darkmode",label:"Toggle Dark Mode",checked:"dark"===f})),c.a.createElement(se.a,{icon:"animations",onClick:L},c.a.createElement("span",{className:"menu-item-name capitalize"},F("Appearance.Animations").toLowerCase()),c.a.createElement(oe,{id:"animations",label:"Toggle Animations",checked:p>0})),c.a.createElement(se.a,{icon:"help",onClick:y},"Telegram Features"),c.a.createElement(se.a,{icon:"bug",href:n.w},"Report Bug")),c.a.createElement(ce.a,{inputId:"telegram-search-input",className:j||g?"with-picker-item":"",value:t||b,focused:D,isLoading:u,placeholder:B,canClose:Boolean(j||g),onChange:a,onReset:d,onFocus:T},k&&c.a.createElement(re.a,{icon:"calendar",title:k,canClose:!0,isMinimized:Boolean(j),className:"search-date",onClick:C,clickArg:M}),j&&c.a.createElement(re.a,{chatOrUserId:j,onClick:i,canClose:!0,clickArg:S}))))})),de=a(20);a(188);var be=Object(s.h)(e=>Object(d.l)(e,["connectionState"]))(({connectionState:e})=>{const t=Object(te.a)();return"connectionStateConnecting"===e&&c.a.createElement("div",{id:"ConnectionState"},c.a.createElement(de.a,{color:"black"}),c.a.createElement("div",{className:"state-text"},t("WaitingForNetwork")))}),ue=a(121),me=a(103),he=a(31),Oe=(e,t,a)=>{const s=Object(c.q)(),n=(e=>Object(c.p)(()=>Object(g.g)(e=>e(),e),[e]))(t),r=Object(he.a)();return Object(me.a)(()=>{let t=!0;n(()=>{s.current=e(),t||r()}),t=!1},a),s.current},je=a(158),ge=a(178);var fe=Object(c.h)(Object(s.h)(e=>{const{chats:{byId:t},users:{byId:a},chatFolders:{byId:s,orderedIds:n},lastSyncTime:c}=e;return{chatsById:t,usersById:a,chatFoldersById:s,orderedFolderIds:n,lastSyncTime:c}},(e,t)=>Object(d.l)(t,["loadChatFolders"]))(({chatsById:e,usersById:t,chatFoldersById:a,orderedFolderIds:s,lastSyncTime:n,loadChatFolders:r})=>{const o=Object(c.q)(null),[i,l]=Object(c.r)(0);Object(c.n)(()=>{n&&r()},[n,r]);const b=Object(c.p)(()=>s?s.map(e=>a[e]||{}).filter(Boolean):void 0,[a,s]),u=Oe(()=>{if(!b||!b.length)return;const a=Object.keys(e).map(Number),s=b.map(s=>{const{unreadDialogsCount:n,hasActiveDialogs:c}=Object(m.p)(e,t,s,a)||{};return{id:s.id,badgeCount:n,isBadgeActive:c}});return Object(d.c)(s,"id")},3e3,[b,e,t]),O=Object(c.p)(()=>{if(b&&b.length)return[{title:"All"},...b.map(e=>({title:e.title,...u&&u[e.id]}))]},[b,u]),j=Object(c.m)(e=>{l(e)},[]);Object(c.n)(()=>{O&&O.length&&i>=O.length&&l(0)},[i,O]),Object(c.n)(()=>{if(o.current&&h.k&&O&&O.length)return Object(ue.b)(o.current,{onSwipe:(e,t)=>{t===ue.a.Left?l(Math.min(i+1,O.length-1)):t===ue.a.Right&&l(Math.max(0,i-1))}})},[i,O]);const{shouldRender:g,transitionClassNames:f}=Object(Y.a)(!s,void 0,!0),p=Object(te.a)();function I(){const e=Object.values(a).find(({title:e})=>e===O[i].title);return e&&0!==i?c.a.createElement(ge.a,{folderType:"folder",folderId:e.id,noChatsText:p("FilterNoChatsToDisplay")}):c.a.createElement(ge.a,{folderType:"all"})}return c.a.createElement("div",{className:"ChatFolders"},O&&O.length?c.a.createElement(je.a,{tabs:O,activeTab:i,onSwitchTab:j}):g?c.a.createElement("div",{className:Object(K.a)("tabs-placeholder",f)}):void 0,c.a.createElement(X.a,{ref:o,name:"slide",activeKey:i,renderCount:O?O.length:void 0},I))})),pe=a(12),Ie=a(17),ve=a(16);var ye=e=>{const t=Object(Ie.a)(pe.a.Extra,"LeftSearch");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Ce=e=>{const t=Object(Ie.a)(pe.a.Extra,"ContactList");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)},we=a(47);a(200);let Ee;var Me=Object(c.h)(({isShown:e,onNewPrivateChat:t,onNewChannel:a,onNewGroup:s})=>{const[n,r]=Object(c.r)(!1);Object(c.n)(()=>{e||r(!1)},[e]);const o=Object(te.a)(),i=Object(K.a)("NewChatButton",e&&"revealed",n&&"menu-is-open"),l=Object(c.m)(()=>{Ee&&(clearTimeout(Ee),Ee=void 0)},[]),d=Object(c.m)(()=>{Ee&&(clearTimeout(Ee),Ee=void 0),Ee=window.setTimeout(()=>{r(!1)},750)},[]);return c.a.createElement("div",{className:i,onMouseEnter:l,onMouseLeave:d},c.a.createElement(ne.a,{round:!0,color:"primary",className:n?"active":"",onClick:()=>{r(!n)},ariaLabel:n?"Close":"Create new chat",tabIndex:-1},c.a.createElement("i",{className:"icon-new-chat-filled"}),c.a.createElement("i",{className:"icon-close"})),c.a.createElement(we.a,{isOpen:n,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},c.a.createElement(se.a,{icon:"channel",onClick:a},o("NewChannel")),c.a.createElement(se.a,{icon:"group",onClick:s},o("NewGroup")),c.a.createElement(se.a,{icon:"user",onClick:t},"New Private Chat")))});a(201);const Se=Object.keys(l.d).length/2;let ke;var Ne=Object(c.h)(({content:e,searchQuery:t,searchDate:a,contactsFilter:s,onSearchQuery:n,onContentChange:r,onReset:o})=>{const[i,d]=Object(c.r)(h.k),b=Object(c.q)(!1),u=Object(c.m)(()=>{r(l.d.Settings)},[r]),m=Object(c.m)(()=>{r(l.d.Contacts)},[r]),O=Object(c.m)(()=>{r(l.d.NewChannelStep1)},[r]),j=Object(c.m)(()=>{r(l.d.NewGroupStep1)},[r]),g=Object(c.m)(()=>{r(l.d.Archived)},[r]),f=Object(c.m)(()=>{e===l.d.ChatList&&(b.current=!0,d(!0))},[e]),p=Object(c.m)(()=>{b.current=!1,ke&&(clearTimeout(ke),ke=void 0),ke=window.setTimeout(()=>{b.current||d(!1)},250)},[]);return Object(c.n)(()=>{let t;return e!==l.d.ChatList?t=window.setTimeout(()=>{d(!1)},250):(b.current||h.k)&&d(!0),()=>{t&&(clearTimeout(t),t=void 0)}},[e]),c.a.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.k?void 0:f,onMouseLeave:h.k?void 0:p},c.a.createElement(le,{content:e,contactsFilter:s,onSearchQuery:n,onSelectSettings:u,onSelectContacts:m,onSelectArchived:g,onReset:o}),c.a.createElement(be,null),c.a.createElement(X.a,{name:"zoom-fade",renderCount:Se,activeKey:e},()=>{switch(e){case l.d.ChatList:return c.a.createElement(fe,null);case l.d.GlobalSearch:return c.a.createElement(ye,{searchQuery:t,searchDate:a,onReset:o});case l.d.Contacts:return c.a.createElement(Ce,{filter:s});default:return}}),c.a.createElement(Me,{isShown:i,onNewPrivateChat:m,onNewChannel:O,onNewGroup:j}))});var Pe=e=>{const t=Object(Ie.a)(pe.a.Extra,"Settings");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Te=e=>{const t=Object(Ie.a)(pe.a.Extra,"NewChat");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Ae,xe=e=>{const t=Object(Ie.a)(pe.a.Extra,"ArchivedChats");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};a(202);!function(e){e[e.Main=0]="Main",e[e.Settings=1]="Settings",e[e.Archived=2]="Archived",e[e.NewGroup=3]="NewGroup",e[e.NewChannel=4]="NewChannel"}(Ae||(Ae={}));const Re=Object.keys(Ae).length/2;var Le=Object(c.h)(Object(s.h)(e=>{const{query:t,date:a}=e.globalSearch;return{searchQuery:t,searchDate:a}},(e,t)=>Object(d.l)(t,["setGlobalSearchQuery","setGlobalSearchChatId","resetChatCreation","setGlobalSearchDate","loadPasswordInfo","clearTwoFaError"]))(({searchQuery:e,searchDate:t,setGlobalSearchQuery:a,setGlobalSearchChatId:s,resetChatCreation:n,setGlobalSearchDate:r,loadPasswordInfo:o,clearTwoFaError:i})=>{const[d,b]=Object(c.r)(l.d.ChatList),[u,m]=Object(c.r)(l.m.Main),[O,j]=Object(c.r)(""),[g,f]=Object(c.r)(0);let p=Ae.Main;switch(d){case l.d.Archived:p=Ae.Archived;break;case l.d.Settings:p=Ae.Settings;break;case l.d.NewChannelStep1:case l.d.NewChannelStep2:p=Ae.NewChannel;break;case l.d.NewGroupStep1:case l.d.NewGroupStep2:p=Ae.NewGroup}const I=Object(c.m)(e=>{if(d!==l.d.NewGroupStep2||e){if(d===l.d.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(d===l.d.Settings)switch(u){case l.m.EditProfile:case l.m.Folders:case l.m.General:case l.m.Notifications:case l.m.Privacy:case l.m.Language:return void m(l.m.Main);case l.m.GeneralChatBackground:return void m(l.m.General);case l.m.GeneralChatBackgroundColor:return void m(l.m.GeneralChatBackground);case l.m.PrivacyPhoneNumber:case l.m.PrivacyLastSeen:case l.m.PrivacyProfilePhoto:case l.m.PrivacyForwarding:case l.m.PrivacyGroupChats:case l.m.PrivacyActiveSessions:case l.m.PrivacyBlockedUsers:case l.m.TwoFaDisabled:case l.m.TwoFaEnabled:case l.m.TwoFaCongratulations:return void m(l.m.Privacy);case l.m.PrivacyPhoneNumberAllowedContacts:case l.m.PrivacyPhoneNumberDeniedContacts:return void m(l.m.PrivacyPhoneNumber);case l.m.PrivacyLastSeenAllowedContacts:case l.m.PrivacyLastSeenDeniedContacts:return void m(l.m.PrivacyLastSeen);case l.m.PrivacyProfilePhotoAllowedContacts:case l.m.PrivacyProfilePhotoDeniedContacts:return void m(l.m.PrivacyProfilePhoto);case l.m.PrivacyForwardingAllowedContacts:case l.m.PrivacyForwardingDeniedContacts:return void m(l.m.PrivacyForwarding);case l.m.PrivacyGroupChatsAllowedContacts:case l.m.PrivacyGroupChatsDeniedContacts:return void m(l.m.PrivacyGroupChats);case l.m.TwoFaNewPassword:return void m(l.m.TwoFaDisabled);case l.m.TwoFaNewPasswordConfirm:return void m(l.m.TwoFaNewPassword);case l.m.TwoFaNewPasswordHint:return void m(l.m.TwoFaNewPasswordConfirm);case l.m.TwoFaNewPasswordEmail:return void m(l.m.TwoFaNewPasswordHint);case l.m.TwoFaNewPasswordEmailCode:return void m(l.m.TwoFaNewPasswordEmail);case l.m.TwoFaChangePasswordCurrent:case l.m.TwoFaTurnOff:case l.m.TwoFaRecoveryEmailCurrentPassword:return void m(l.m.TwoFaEnabled);case l.m.TwoFaChangePasswordNew:return void m(l.m.TwoFaChangePasswordCurrent);case l.m.TwoFaChangePasswordConfirm:return void m(l.m.TwoFaChangePasswordNew);case l.m.TwoFaChangePasswordHint:return void m(l.m.TwoFaChangePasswordConfirm);case l.m.TwoFaRecoveryEmail:return void m(l.m.TwoFaRecoveryEmailCurrentPassword);case l.m.TwoFaRecoveryEmailCode:return void m(l.m.TwoFaRecoveryEmail);case l.m.FoldersCreateFolder:case l.m.FoldersEditFolder:return void m(l.m.Folders)}b(l.d.ChatList),j(""),a({query:""}),r({date:void 0}),s({id:void 0}),n(),setTimeout(()=>{f(Date.now())},250)}else b(l.d.NewGroupStep1)},[d,a,s,r,n,u]),v=Object(c.m)(t=>{d!==l.d.Contacts?(b(l.d.GlobalSearch),t!==e&&a({query:t})):j(t)},[d,a,e]);return Object(c.n)(()=>d!==l.d.ChatList?Object(Z.a)(()=>I()):void 0,[d,I]),Object(c.n)(()=>{i(),u===l.m.Privacy&&o()},[i,o,u]),c.a.createElement(X.a,{id:"LeftColumn",name:h.f?"slide-layers":"push-slide",renderCount:Re,activeKey:p},()=>{switch(p){case Ae.Archived:return c.a.createElement(xe,{onReset:I});case Ae.Settings:return c.a.createElement(Pe,{currentScreen:u,onScreenSelect:m,onReset:I});case Ae.NewChannel:return c.a.createElement(Te,{key:g,isChannel:!0,content:d,onContentChange:b,onReset:I});case Ae.NewGroup:return c.a.createElement(Te,{key:g,content:d,onContentChange:b,onReset:I});default:return c.a.createElement(Ne,{content:d,searchQuery:e,searchDate:t,contactsFilter:O,onContentChange:b,onSearchQuery:v,onReset:I})}})})),Fe=a(126),De=a(13),Be=a(49);var Ue=()=>{const[e,t]=Object(c.r)(Be.a.get());return Object(c.n)(()=>{const e=Object(g.g)(()=>{t(Be.a.get())},250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),e},He=a(38);function qe(e,t){const a=Object(He.a)(e,!0),s=Object(c.q)(),n=Object(he.a)(),r=null!=e;return r&&s.current&&(clearTimeout(s.current),s.current=void 0),Object(me.a)(()=>{t&&!r&&a&&!s.current&&(s.current=window.setTimeout(()=>{s.current=void 0,n()},t))},[e]),r||t&&!s.current?e:a}function Ge(e,t){const a=e<=n.cb?16:32,s=function(e){if(e>n.Z){const t=Math.min(Math.max(.25*e,288),424),a=Math.min(.25*e,424);return Math.min(e-t-a,728)}if(e>n.Y){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,728)}if(e>728)return 728;return e}(e),c=e<=n.cb?54:64,r=t?s-a-c:s-a,o=e>n.cb?Math.min(s-a,512):s-a,i=o/r,l=r/o;return{composerHiddenScale:i,toolbarHiddenScale:l,composerTranslateX:t?c/2*l:0,toolbarTranslateX:t?c/2*-1*i:0,unpinHiddenScale:o/258,toolbarForUnpinHiddenScale:258/o}}var _e=a(133),ze=a(131);function We(e,t=!1,a=!1){const s=Object(He.a)(e,t);return a||null!=e?e:s}var Ve=a(44),$e=a(98),Qe=a(114);var Ke=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"HeaderMenuContainer",!t);return a?c.a.createElement(a,e):void 0};var Ye=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=Boolean(n&&Object(m.ib)(n));if(n&&n.isRestricted)return{noMenu:!0};const r=Object(o.O)(e,t),l="thread"===s&&a===i.MAIN_THREAD_ID,d="thread"===s&&a!==i.MAIN_THREAD_ID,b=Object(o.V)(e),u=Boolean(Object(o.K)(e,t)),O=Boolean(l&&n&&(c||Object(m.mb)(n))&&n.isNotJoined),j=l||d,g=l&&!r&&!O,f=!Object(o.R)(e),p=l&&!O;return{noMenu:!(h.f&&O||h.f&&j||g||f||p),isChannel:c,isRightColumnShown:b,canStartBot:u,canSubscribe:O,canSearch:j,canMute:g,canSelect:f,canLeave:p}},(e,t)=>Object(d.l)(t,["joinChannel","sendBotCommand","openLocalTextSearch"]))(({chatId:e,threadId:t,noMenu:a,isChannel:s,canStartBot:n,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,isRightColumnShown:b,joinChannel:u,sendBotCommand:m,openLocalTextSearch:O})=>{const j=Object(c.q)(null),[g,f]=Object(c.r)(!1),[p,I]=Object(c.r)(void 0),v=Object(c.m)(()=>{f(!0);const e=j.current.getBoundingClientRect();I({x:e.right,y:e.bottom})},[]),y=Object(c.m)(()=>{f(!1)},[]),C=Object(c.m)(()=>{I(void 0)},[]),w=Object(c.m)(()=>{u({chatId:e})},[u,e]),E=Object(c.m)(()=>{m({command:"/start"})},[m]),M=Object(c.m)(()=>{if(O(),h.f){document.querySelector("#MobileSearch input").focus()}else setTimeout(()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()},400)},[O]),S=Object(te.a)();return c.a.createElement("div",{className:"HeaderActions"},!h.f&&r&&c.a.createElement(ne.a,{size:"tiny",ripple:!0,fluid:!0,onClick:w},S(s?"Subscribe":"Join Group")),!h.f&&n&&c.a.createElement(ne.a,{size:"tiny",ripple:!0,fluid:!0,onClick:E},S("Start")),!h.f&&o&&c.a.createElement(ne.a,{round:!0,ripple:b,color:"translucent",size:"smaller",onClick:M,ariaLabel:"Search in this chat"},c.a.createElement("i",{className:"icon-search"})),(h.f||!r)&&c.a.createElement(ne.a,{ref:j,className:g?"active":"",round:!0,ripple:!h.f,size:"smaller",color:"translucent",disabled:a,ariaLabel:"More actions",onClick:v},c.a.createElement("i",{className:"icon-more"})),p&&c.a.createElement(Ke,{chatId:e,threadId:t,isOpen:g,anchor:p,isChannel:s,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,onSubscribeChannel:w,onSearchClick:M,onClose:y,onCloseAnimationEnd:C}))})),Je=a(105),Ze=a(37),Xe=a(97),et=a(36);function tt(e){const t=e&&Object(m.E)(e),{sticker:a}=e&&e.content||{},s=t&&a&&!Object(h.o)()&&t.includes("image/webp"),[r,o]=Object(c.r)(et.a),i=e&&e.id;return Object(c.o)(()=>{s&&Object(et.c)("b64-"+i,t).then(o).catch(e=>{n.o&&console.error(e)})},[i,s,t]),s?r:t}var at=a(107),st=a(35),nt=a(28);function ct(e,t,a,s,n){return`M${e},${t+n}a${n},${n},0,0,1,\n ${a},0v${s-2*n}a${n},${n},0,0,1,${-a},0Z`}var rt=Object(c.h)(({count:e,index:t})=>{const a=Object(c.q)(null),s=Object(c.p)(()=>function(e,t){const a=e-t-1,s=function(e){let t=8;1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5);return t}(e),n=function(e,t){let a=36;1===e?a=36:2===e?a=17:3===e?a=1===t?12:11:(4===e||e>3)&&(a=7.5);return a}(e,a),c=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,s),r="clipPath"+e,o=function(e,t,a){let s="";if(3===a)s=ct(0,0,2,t,1)+ct(0,12,2,t+1,1)+ct(0,25,2,t,1);else for(let e=0;e\n \n `}(r,s,e),i=function(e,t,a){if(1===a)return 0;if(2===a)return 0===e?0:t+2;return 3===a?0===e?0:1===e?12:25:(t+2)*e}(a,s,e),l=function(e,t,a,s){if(t<=4)return 0;if(e<=1)return 0;if(e>=t-2)return s-36;return(a+4)/2+(e-2)*(a+2)}(a,e,s,c);return{markHeight:n,clipPath:o,markTranslateY:i,trackTranslateY:l,trackHeight:c,clipPathId:r}}(e,t),[e,t]);if(Object(c.n)(()=>{if(!a.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:n,markTranslateY:c,clipPathId:r,clipPath:o}=s,i=a.current.firstElementChild;if(a&&a.current){const s=a.current,{style:l}=s;l.height=e+"px",l.transform=`translateY(-${t}px)`,l.clipPath=`url("#${r}")`;const d=s.querySelector("svg"),b=s.querySelector("div"),u=s.querySelector("defs");d||i&&(i.innerHTML=` ${o} `),u&&(u.innerHTML=o),b&&(b.style.height=n+"px",b.style.transform=`translateY(${c}px)`)}},[s]),1===e)return c.a.createElement("div",{className:"pinned-message-border"},c.a.createElement("div",{className:"pinned-message-border-wrapper-1",ref:a}));const{trackHeight:n,trackTranslateY:r,markHeight:o,markTranslateY:i,clipPathId:l}=s;return c.a.createElement("div",{className:Object(K.a)("pinned-message-border",e>4&&"pinned-message-border-mask")},c.a.createElement("div",{className:"pinned-message-border-wrapper",ref:a,style:`clip-path: url("#${l}"); width: 2px;\n height: ${n}px; transform: translateY(-${r}px);`},c.a.createElement("span",null),c.a.createElement("div",{className:"pinned-message-border-mark",style:`height: ${o}px; transform: translateY(${i}px);`})))});var ot=Object(c.h)(({message:e,count:t,index:a,customTitle:s,className:n,onUnpinMessage:r,onClick:o,onAllPinnedClick:i})=>{const l=tt(e),d=Object(Xe.a)(Object(m.D)(e,"pictogram")),b=Object(m.M)(e,Boolean(l)),[u,h,O]=Object(nt.a)(),j=Object(c.m)(()=>{O(),r&&r(e.id)},[O,r,e.id]),g=Object(te.a)();return c.a.createElement("div",{className:Object(K.a)("HeaderPinnedMessage-wrapper",n)},t>1&&c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:g("EventLogFilterPinnedMessages"),onClick:i},c.a.createElement("i",{className:"icon-pin-list"})),r&&c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:g("UnpinMessageAlertTitle"),className:"unpin-button",onClick:h},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(at.a,{isOpen:u,onClose:O,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:j}),c.a.createElement("div",{className:"HeaderPinnedMessage",onClick:o},c.a.createElement(rt,{count:t,index:a}),l&&function(e,t){const{width:a,height:s}=Object(Je.k)();return c.a.createElement("img",{src:t||e,width:a,height:s,alt:""})}(l,d),c.a.createElement("div",{className:"message-text"},c.a.createElement("div",{className:"title"},s||`${g("PinnedMessage")} ${a>0?"#"+(t-a):""}`),c.a.createElement("p",null,Object(Ze.a)(b))),c.a.createElement(st.a,null)))}),it=a(48),lt=a(165);a(205);var dt=Object(s.h)((e,{message:t})=>{const a=Object(o.qb)(e,t);return{senderName:a?Object(m.U)(a):void 0}},(e,t)=>Object(d.l)(t,["focusMessage","closeAudioPlayer"]))(({message:e,className:t,noUi:a,senderName:s,focusMessage:n,closeAudioPlayer:r})=>{const o=it.c(Object(m.D)(e,"inline")),{playPause:i,isPlaying:l}=Object(lt.a)(Object(m.A)(e),Object(m.r)(e),o,void 0,void 0,!0),d=Object(c.m)(()=>{n({chatId:e.chatId,messageId:e.id})},[n,e.chatId,e.id]),b=Object(c.m)(()=>{l&&i(),r()},[r,l,i]),u=Object(te.a)();if(a)return;const O=Object(m.u)(e);return c.a.createElement("div",{className:Object(K.a)("AudioPlayer",t)},c.a.createElement(ne.a,{round:!0,ripple:!h.f,color:"translucent",size:"smaller",className:Object(K.a)("toggle-play",l?"pause":"play"),onClick:i,ariaLabel:l?"Pause audio":"Play audio"},c.a.createElement("i",{className:"icon-play"}),c.a.createElement("i",{className:"icon-pause"})),c.a.createElement("div",{className:"AudioPlayer-content",onClick:d},O?function(e){const{title:t,performer:a,fileName:s}=e;return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title"},Object(Ze.a)(t||s)),a&&c.a.createElement("div",{className:"subtitle"},Object(Ze.a)(a)))}(O):function(e,t){return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title"},t&&Object(Ze.a)(t)),c.a.createElement("div",{className:"subtitle"},e))}(u("AttachAudio"),s),c.a.createElement(st.a,null)),c.a.createElement(ne.a,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:b,ariaLabel:"Close player"},c.a.createElement("i",{className:"icon-close"})))});a(206);var bt=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const{isLeftColumnShown:n,lastSyncTime:c}=e,{byId:r}=e.chats,l=Object(o.f)(e,t),{typingStatus:d}=l||{},{chatId:b,messageId:u}=e.audioPlayer,h=b&&u?Object(o.k)(e,b,u):void 0,O=Object(o.Ab)(e,t,a);let j;if("pinned"===s){const a=Object(o.gb)(e,t);j=a&&a.length}else if("scheduled"===s){const a=Object(o.lb)(e,t);j=a&&a.length}else if("thread"===s&&a!==i.MAIN_THREAD_ID){const s=Object(o.zb)(e,t,a);s&&(j=s.messagesCount)}let g={typingStatus:d,isLeftColumnShown:n,isRightColumnShown:Object(o.V)(e),isSelectModeActive:Object(o.R)(e),audioMessage:h,chatTitleLength:l&&Object(m.l)(l).length,chatsById:r,originChatId:O?O.id:t,messagesCount:j,isChatWithSelf:Object(o.O)(e,t),isChatWithBot:l&&Object(o.N)(e,l),lastSyncTime:c};const f=Object(o.m)(e,t);if("thread"===s&&f)if(a===i.MAIN_THREAD_ID){const s=Object(o.gb)(e,t);if(s&&s.length){const t=f[s[0]],{canUnpin:n}=t&&Object(o.b)(e,t,a)||{};g={...g,pinnedMessageIds:s,messagesById:f,canUnpin:n}}}else{const s=Object(o.Bb)(e,t,a),n=s?Object(o.k)(e,t,s):void 0,c=n?Object(o.J)(e,n):void 0,r=c?Object(m.U)(c):void 0;g={...g,pinnedMessageIds:s,messagesById:f,canUnpin:!1,topMessageTitle:r}}return g},(e,t)=>Object(d.l)(t,["openChatWithInfo","pinMessage","focusMessage","openChat","loadPinnedMessages","toggleLeftColumn","exitMessageSelectMode"]))(({chatId:e,threadId:t,messageListType:a,pinnedMessageIds:s,messagesById:r,canUnpin:o,topMessageTitle:l,typingStatus:d,isSelectModeActive:b,isLeftColumnShown:u,isRightColumnShown:O,audioMessage:j,chatTitleLength:g,chatsById:f,originChatId:p,messagesCount:I,isChatWithSelf:v,isChatWithBot:y,lastSyncTime:C,openChatWithInfo:w,pinMessage:E,focusMessage:M,openChat:S,loadPinnedMessages:k,toggleLeftColumn:N,exitMessageSelectMode:P})=>{const[T,A]=Object(c.r)(0),x=Array.isArray(s)?s[T]:s,R=r&&x?r[x]:void 0,L=Array.isArray(s)?s.length:s?1:0;Object(c.n)(()=>{t===i.MAIN_THREAD_ID&&C&&k({chatId:e})},[e,k,C,t]),Object(c.n)(()=>{A(0)},[e]),Object(c.n)(()=>{A(L?Object(_e.a)(L,T):-1)},[L,T]),Object(ze.a)(e,x,R);const{width:F}=Ue(),D=F<=n.Y,B=F>=n.cb&&u,U=Object(c.q)(null),H=Object(c.q)(!0),q=Object(c.m)(()=>{w({id:e})},[w,e]),G=Object(c.m)(t=>{E({chatId:e,messageId:t,isUnpin:!0})},[E,e]),_=Object(c.m)(()=>{if(R){M({chatId:R.chatId,threadId:t,messageId:R.id});const e=Object(_e.a)(L,T+1);A(e)}},[R,M,t,L,T]),z=Object(c.m)(()=>{S({id:e,threadId:i.MAIN_THREAD_ID,type:"pinned"})},[S,e]),W=Object(c.m)(()=>{if(h.f){const e=document.getElementById(n.u);e&&e.blur()}t!==i.MAIN_THREAD_ID||"thread"!==a?("scheduled"===a&&b&&P(),S({id:p,threadId:i.MAIN_THREAD_ID})):h.f?S({id:void 0}):N()},[S,p,t,a,N,b,P]),V=Object(c.p)(()=>{if(!D||!f)return;let e=!1;const t=Object.values(f).reduce((t,a)=>{if(Object(m.gb)(a))return t;const s=a.unreadCount||0;return!s||a.isMuted&&!a.unreadMentionsCount||(e=!0),t+s},0);return t?{isActive:e,totalCount:t}:void 0},[D,f]),$=F>=n.Y&&Fn.cb&&F30),Q=$||F>n.Z&&F{const e=U.current;if(e)return Q&&oe?void(O||$?(H.current&&(e.classList.add("tools-stacked","animated"),H.current=!1),setTimeout(()=>{e.classList.remove("animated")},350)):(e.classList.remove("tools-stacked"),H.current=!0)):(e.classList.remove("tools-stacked","animated"),void(H.current=!0))},[Q,oe,$,O]);const ie=Object(te.a)();function le(){return"thread"===a&&t===i.MAIN_THREAD_ID?c.a.createElement(c.a.Fragment,null,D&&de(B,V),c.a.createElement("div",{className:"chat-info-wrapper",onClick:q},Object(m.kb)(e)?c.a.createElement($e.a,{userId:e,typingStatus:d,withFullInfo:y,withMediaViewer:!0,withUpdatingStatus:!0}):c.a.createElement(Qe.a,{chatId:e,typingStatus:d,withMediaViewer:!0,withFullInfo:!0,withUpdatingStatus:!0}))):"thread"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,ie("CommentsCount",I))):"pinned"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,ie("PinnedMessagesCount",I))):"scheduled"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,v?ie("Reminders"):ie("messages",I))):void 0}function de(e=!1,t){return c.a.createElement("div",{className:"back-button"},c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",onClick:W,ariaLabel:e?"Close":"Back"},c.a.createElement("div",{className:Object(K.a)("animated-close-icon",!e&&"state-back")})),t&&c.a.createElement("div",{className:"unread-count "+(t.isActive?"active":"")},Object(Ve.b)(t.totalCount)))}return c.a.createElement("div",{className:"MiddleHeader",ref:U},c.a.createElement(X.a,{name:"slide-fade",activeKey:"thread"===a?t:1},le),c.a.createElement("div",{className:"header-tools"},ae&&ce&&!J&&c.a.createElement(ot,{key:e,message:ce,count:L,index:T,customTitle:re,className:se,onUnpinMessage:o?G:void 0,onClick:_,onAllPinnedClick:z}),J&&ee&&c.a.createElement(dt,{key:Object(m.A)(ee),message:ee,className:Z}),c.a.createElement(Ye,{chatId:e,threadId:t,messageListType:a})))})),ut=a(151);function mt(e){return"albumId"in e}function ht(e,t){let a,s=[],n={originalDate:e[0].date,datetime:Number(Object(A.j)(1e3*e[0].date)),senderGroups:[s]};const c=[n];return e.forEach((r,o)=>{r.isInAlbum?a?(a.messages.push(r),r.content.text&&(a.mainMessage=r)):a={albumId:r.groupedId,messages:[r],mainMessage:r}:s.push(r);const i=e[o+1];if(!a||i&&i.groupedId&&i.groupedId===a.albumId||(s.push(a),a=void 0),i){const e=Number(Object(A.j)(1e3*i.date));n.datetime!==e?(n={originalDate:i.date,datetime:e,senderGroups:[]},c.push(n),s=[],n.senderGroups.push(s)):(i.id===t||r.senderId!==i.senderId||r.isOutgoing!==i.isOutgoing||Object(m.cb)(r)||Object(m.cb)(i)||r.forwardInfo&&i.forwardInfo&&(r.forwardInfo.senderUserId!==i.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==i.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==i.forwardInfo.hiddenUserName)||r.inlineButtons||i.inlineButtons)&&(s=[],n.senderGroups.push(s))}}),c}var Ot=a(96);function jt(){const[e,t]=Object(nt.a)(!1),a=(s=1e3,n=!1,Object(c.p)(()=>Object(g.a)(e=>e(),s,n,r),[s,n,r]));var s,n,r;return{isScrolled:e,updateStickyDates:Object(c.m)((e,s)=>{t(),document.body.classList.contains("is-scrolling-messages")||Object(g.b)(()=>{document.body.classList.add("is-scrolling-messages")}),a(()=>{Object(g.b)(()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const a=function(e,t){const a=e.querySelectorAll(".sticky-date"),s=e.scrollTop;return Array.from(a).find(e=>{const{offsetTop:a,offsetHeight:n}=e,c=a-s;return-n<=c&&c<=(t?60:10)})}(e,s);a&&a.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")})})},[t,a])}}var gt=a(146),ft=a(115);let pt=!1;var It=({containerRef:e,className:t,messageIds:a,containerHeight:s,listItemElementsRef:r,focusingId:o,anchorIdRef:i,anchorTopRef:l,loadMoreForwards:d,loadMoreBackwards:b,isViewportNewest:u,firstUnreadId:m,onFabToggle:h,children:O})=>{const j=Object(c.q)(null),g=Object(c.q)(null),f=Object(c.q)(null),p=Object(c.m)(()=>{if(pt)return;if(!a||!a.length)return void h(!1);if(!u)return void h(!0);const{offsetHeight:t,scrollHeight:s,scrollTop:n}=e.current,c=s-n-t;h(m?!(0===c):!(c<=50))},[a,u,e,h,m]),{observe:I,freeze:v,unfreeze:y}=Object(Ot.a)({rootRef:e,margin:n.T},t=>{if(!d||!b)return;const a=t.find(({isIntersecting:e})=>e);if(!a)return;const{target:s}=a;"backwards-trigger"===s.className?(Object(gt.a)(e.current),b()):"forwards-trigger"===s.className&&s.dataset.isActive&&(Object(gt.a)(e.current),d())});Object(Ot.c)(j,I),Object(Ot.c)(g,I);const{observe:C,freeze:w,unfreeze:E}=Object(Ot.a)({rootRef:e,margin:50},([{target:e}])=>{e.dataset.isActive&&p()});return Object(Ot.c)(f,C),Object(me.a)(()=>{o?(v(),w()):(E(),y())},[o]),Object(me.a)(()=>{if(!r.current)return;const e=r.current.filter(e=>a.includes(Number(e.dataset.messageId))),t=e[1]||e[0];t&&(i.current=t.id,l.current=t.getBoundingClientRect().top)},[a,s]),Object(me.a)(()=>{pt=!0,setTimeout(()=>{pt=!1},100)},[a]),Object(c.n)(p,[m]),c.a.createElement("div",{className:t,teactFastList:!0},c.a.createElement("div",{ref:j,key:"backwards-trigger",className:"backwards-trigger"}),O,c.a.createElement("div",{ref:g,key:"forwards-trigger",className:"forwards-trigger","data-is-active":!u}),c.a.createElement("div",{ref:f,key:"fab-trigger",className:"fab-trigger","data-is-active":u}))},vt=a(132),yt=a(135);function Ct(e){return"number"==typeof e}function wt(e){return e?175:100}function Et(e){const t=Object(m.sb)(e),a=Object(m.pb)(e),s=Object(m.G)(e)||Object(m.Q)(e),n=Object(m.O)(e),c=Boolean(Object(m.Q)(e)),{width:r,height:o}=s?Object(Je.f)(s,t,a,c):Object(Je.h)(n,t,a),i=wt(Boolean(Object(m.N)(e)));let l=1;re+t,t)}function At(e,t,a){return ea?a:e}function xt(e){const t={width:0,height:0};return e.forEach(({dimensions:e,sides:a})=>{a&kt&&(t.width=e.width+e.x),a&Nt&&(t.height=e.height+e.y)}),t}function Rt(e,t,a,s){const c=a.messages.map(e=>{const t=Et(e);return t.width/t.height});const r=function(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}(c),o=function(e){return e.reduce((e,t)=>t+e,1)/e.length}(c),i=c.length,l=c.some(e=>e>2),d=function(e,t,a){return a<=n.cb?a/100*69-(t?1.625:0)*Je.c:((e?30:29)-(t?1.625:0))*Je.c}(e,t,s);let b;const u={ratios:c,proportions:r,averageRatio:o,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return b=i>=5||l?function({ratios:e,averageRatio:t,maxWidth:a,minWidth:s,spacing:n,maxHeight:c=4*a/3}){const r=function(e,t){return e.map(e=>t>1.1?At(e,1,2.75):At(e,.6667,1))}(e,t),o=e.length,i=new Array(o),l=[],d=e=>{const t=[];let s=0;e.forEach(e=>{t.push(((e,t)=>{const s=Tt(r.slice(e,e+t),0);return(a-(t-1)*n)/s})(s,e)),s+=e}),l.push({lineCounts:e,heights:t})};for(let e=1;e!==o;++e){const t=o-e;e<=3&&t<=3&&d([e,t])}for(let e=1;e!==o-1;++e)for(let a=1;a!==o-e;++a){const s=o-e-a;e<=3&&a<=(t<.85?4:3)&&s<=3&&d([e,a,s])}for(let e=1;e!==o-1;++e)for(let t=1;t!==o-e;++t)for(let a=1;a!==o-e-t;++a){const s=o-e-t-a;e<=3&&t<=3&&a<=3&&s<=4&&d([e,t,a,s])}let b,u=0;for(let e=0;e{for(let e=1;e!==r;++e)if(a[e-1]>a[e])return 1.5;return 1})(),m=Math.abs(o-c)*i*d;(!b||m1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=Math.round(Math.min(a/t[0],Math.min(a/t[1],(n-s)/2)));return[{dimensions:{x:0,y:0,width:a,height:c},sides:Pt|St|kt},{dimensions:{x:0,y:c+s,width:a,height:c},sides:Pt|Nt|kt}]}(e):"ww"===a||"qq"===a?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=(a-s)/2,r=Math.round(Math.min(c/t[0],Math.min(c/t[1],n)));return[{dimensions:{x:0,y:0,width:c,height:r},sides:St|Pt|Nt},{dimensions:{x:c+s,y:0,width:c,height:r},sides:St|kt|Nt}]}(e):function(e){const{ratios:t,minWidth:a,maxWidth:s,spacing:n,maxHeight:c}=e,r=Math.round(1.5*a),o=Math.min(Math.round(Math.max(.4*(s-n),(s-n)/t[0]/(1/t[0]+1/t[1]))),s-n-r),i=s-o-n,l=Math.min(c,Math.round(Math.min(i/t[0],o/t[1])));return[{dimensions:{x:0,y:0,width:i,height:l},sides:St|Pt|Nt},{dimensions:{x:i+n,y:0,width:o,height:l},sides:St|kt|Nt}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:a,ratios:s,maxWidth:n,minWidth:c}=e,r=t,o=Math.round(Math.min((t-a)/2,s[1]*(n-a)/(s[2]+s[1]))),i=r-o-a,l=Math.max(c,Math.round(Math.min((n-a)/2,Math.min(o*s[2],i*s[1])))),d=Math.min(Math.round(r*s[0]),n-a-l);return[{dimensions:{x:0,y:0,width:d,height:r},sides:St|Pt|Nt},{dimensions:{x:d+a,y:0,width:l,height:i},sides:St|kt},{dimensions:{x:d+a,y:i+a,width:l,height:o},sides:Nt|kt}]}(e):function(e){const{maxWidth:t,ratios:a,maxHeight:s,spacing:n}=e,c=t,r=Math.round(Math.min(c/a[0],.66*(s-n))),o=(t-n)/2,i=Math.min(s-r-n,Math.round(Math.min(o/a[1],o/a[2])));return[{dimensions:{x:0,y:0,width:c,height:r},sides:Pt|St|kt},{dimensions:{x:0,y:r+n,width:o,height:i},sides:Nt|Pt},{dimensions:{x:o+n,y:r+n,width:c-o-n,height:i},sides:Nt|kt}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:a,maxHeight:s,minWidth:n}){const c=e,r=Math.round(Math.min(c/t[0],.66*(s-a))),o=Math.round((e-2*a)/(t[1]+t[2]+t[3])),i=Math.max(n,Math.round(Math.min(.4*(e-2*a),o*t[1]))),l=Math.round(Math.max(Math.max(n,.33*(e-2*a)),o*t[3])),d=c-i-l-2*a,b=Math.min(s-r-a,o);return[{dimensions:{x:0,y:0,width:c,height:r},sides:Pt|St|kt},{dimensions:{x:0,y:r+a,width:i,height:b},sides:Nt|Pt},{dimensions:{x:i+a,y:r+a,width:d,height:b},sides:Nt},{dimensions:{x:i+a+d+a,y:r+a,width:l,height:b},sides:kt|Nt}]}(e):function({maxHeight:e,ratios:t,maxWidth:a,spacing:s,minWidth:n}){const c=e,r=Math.round(Math.min(c*t[0],.6*(a-s))),o=Math.round((e-2*s)/(1/t[1]+1/t[2]+1/t[3])),i=Math.round(o/t[1]),l=Math.round(o/t[2]),d=c-i-l-2*s,b=Math.max(n,Math.min(a-r-s,o));return[{dimensions:{x:0,y:0,width:r,height:c},sides:St|Pt|Nt},{dimensions:{x:r+s,y:0,width:b,height:i},sides:St|kt},{dimensions:{x:r+s,y:i+s,width:b,height:l},sides:kt},{dimensions:{x:r+s,y:i+l+2*s,width:b,height:d},sides:Nt|kt}]}(e)}(u),{layout:b,containerStyle:xt(b)}}let Lt;function Ft(e){return Lt||(Lt=document.createElement("span"),Lt.style.font='400 12px Roboto, "Helvetica Neue", "Apple Color Emoji", sans-serif',Lt.style.whiteSpace="nowrap",Lt.style.position="absolute",Lt.style.left="-999px",Lt.style.opacity=".01",document.body.appendChild(Lt)),Lt.innerHTML=e,Lt.offsetWidth}function Dt(e,t,a,s,n){Object(c.o)(()=>{if(a&&e.current){const t=e.current.closest(".MessageList");Object(ft.a)(t,e.current,n?"end":"center",20,void 0===s?1500:1e3,s)}},[e,t,a,s,n])}var Bt=a(101),Ut=a(179);var Ht=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ContextMenuContainer",!t);return a?c.a.createElement(a,e):void 0};var qt=Object(c.h)(Object(s.h)((e,{message:t})=>{const a=t.senderId,{targetUserId:s,targetChatId:n}=t.content.action||{},c=t.replyToMessageId,r=c?Object(o.k)(e,t.chatId,c):void 0,i=Object(o.T)(e,t),{direction:l,noHighlight:d}=i&&e.focusedMessage||{},b=Object(o.f)(e,t.chatId);return{sender:b&&(Object(m.ib)(b)||a===t.chatId)?b:a?Object(o.Db)(e,a):void 0,...s&&{targetUser:Object(o.Db)(e,s)},targetChatId:n,targetMessage:r,isFocused:i,...i&&{focusDirection:l,noFocusHighlight:d}}})(({message:e,observeIntersection:t,isEmbedded:a,appearanceOrder:s=0,sender:n,targetUser:r,targetMessage:o,targetChatId:i,isFocused:l,focusDirection:d,noFocusHighlight:b})=>{const u=Object(c.q)(null);Object(Ot.c)(u,t),Object(ze.a)(e.chatId,e.replyToMessageId,o),Dt(u,e.chatId,l,d,b),Object(te.a)();const m=s<=0,[h,O]=Object(nt.a)(m);Object(c.n)(()=>{m||setTimeout(O,10*s)},[s,O,m]);const{transitionClassNames:j}=Object(Y.a)(h,void 0,m,!1),g=Object(Ut.a)(e,n,r,o,i,a?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:f,contextMenuPosition:p,handleBeforeContextMenu:I,handleContextMenu:v,handleContextMenuClose:y,handleContextMenuHide:C}=Object(vt.a)(u),w=void 0!==p;return a?c.a.createElement("span",{className:"embedded-action-message"},Object(Ze.a)(g)):c.a.createElement("div",{ref:u,id:"message"+e.id,className:Object(K.a)("ActionMessage message-list-item",l&&!b&&"focused",w&&"has-menu-open",j),"data-message-id":e.id,onMouseDown:I,onContextMenu:v},c.a.createElement("span",null,g),p&&c.a.createElement(Ht,{isOpen:f,anchor:p,message:e,messageListType:"thread",onClose:y,onCloseAnimationEnd:C}))}));a(207);var Gt=({className:e,message:t,sender:a,title:s,customText:n,observeIntersection:r,onClick:o})=>{const i=Object(c.q)(null),l=Object(Ot.b)(i,r),d=Object(Xe.a)(t&&Object(m.D)(t,"pictogram"),!l),b=t&&"sticker-reply-thumb"+t.id,u=tt(t);Object(te.a)();const h=a&&Object(m.U)(a);return c.a.createElement("div",{ref:i,className:Object(K.a)("EmbeddedMessage",e),onClick:t?o:void 0},u&&function(e,t,a){const{width:s,height:n}=Object(Je.k)();return c.a.createElement("img",{id:e,src:a||t,width:s,height:n,alt:""})}(b,u,d),c.a.createElement("div",{className:"message-text"},c.a.createElement("div",{className:"message-title"},Object(Ze.a)(h||s||" ")),c.a.createElement("p",null,t?Object(m.cb)(t)?c.a.createElement(qt,{message:t,isEmbedded:!0}):Object(Ze.a)(Object(m.M)(t,Boolean(u))):n||" ")))},_t=a(152),zt=a(157),Wt=a(162);a(211);var Vt=({message:e,outgoingStatus:t,signature:a,onClick:s})=>{const n=Object(te.a)();return c.a.createElement("span",{className:"MessageMeta",onClick:s},Boolean(e.views)&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"message-views"},Object(Ve.b)(e.views)),c.a.createElement("i",{className:"icon-channelviews"})),a&&c.a.createElement("span",{className:"message-signature"},Object(Ze.a)(a)),c.a.createElement("span",{className:"message-time"},e.isEdited&&n("EditedMessage")+" ",Object(A.h)(1e3*e.date)),t&&c.a.createElement(Wt.a,{status:t}))},$t=a(104),Qt=a(106),Kt=a(153);a(212);var Yt=({message:e,observeIntersection:t,observeIntersectionForPlaying:a,shouldLoop:s,lastSyncTime:r})=>{const o=Object(c.q)(null),[i,l,d]=Object(nt.a)(),b=e.content.sticker,{isAnimated:u,stickerSetId:h}=b,O=h===n.R,j=Object(Ot.b)(o,t),g=Object(Ot.b)(o,a),f=b.isPreloadedGlobally?"sticker"+b.id:Object(m.D)(e,"inline"),p=tt(e),I=Object(Xe.a)(f,!j,Object(m.C)(e,"inline",!0),r),v=Boolean(I),[y,C]=Object(nt.a)(v),w=u?y:v,{shouldRenderFullMedia:E,transitionClassNames:M}=Object($t.a)(w,"slow"),{width:S,height:k}=Object(Je.l)(b),N=Object(K.a)("thumbnail",!p&&"empty"),P=Object(K.a)("Sticker media-inner",O&&"inactive");return c.a.createElement("div",{ref:o,className:P,onClick:O?void 0:l},!w&&c.a.createElement("img",{id:"sticker-thumb-"+e.id,src:p,width:S,height:k,alt:"",className:N}),!u&&E&&c.a.createElement("img",{id:"sticker-"+e.id,src:I,width:S,height:k,alt:"",className:Object(K.a)("full-media",M)}),u&&v&&c.a.createElement(Qt.a,{key:f,className:Object(K.a)("full-media",M),id:f,animationData:I,size:S,play:g,noLoop:!s,onLoad:C}),c.a.createElement(Kt.a,{isOpen:i,fromSticker:b,onClose:d}))},Jt=a(119),Zt=a(111),Xt=a(136);function ea(e,t){return Object(Xt.a)(Object(m.E)(e),Boolean(t),h.f?n.H:void 0)}var ta=async(e,t,a,s)=>s?"rgba(255,255,255,1)":async function(e,t){const a=new Image;a.src=e,a.width||await new Promise(e=>{a.onload=e});const s=document.createElement("canvas"),n=s.getContext("2d");s.width=a.width,s.height=a.height,n.drawImage(a,0,0,a.width,a.height);const c=t?a.width-1:0,r=a.height-1;return`rgba(${Array.from(n.getImageData(c,r,1,1).data).join(",")})`}(e,t);var aa=a(112);var sa=({id:e,message:t,observeIntersection:a,shouldAutoLoad:s,isInSelectMode:n,isSelected:r,uploadProgress:o,size:i="inline",dimensions:l,shouldAffectAppendix:d,onClick:b,onCancelUpload:u})=>{const h=Object(c.q)(null),O=(Object(m.G)(t)||Object(m.Q)(t)).blobUrl,j=Object(Ot.b)(h,a),[g,f]=Object(c.r)(s),p=g&&j,{mediaData:I,downloadProgress:v}=Object(Zt.a)(Object(m.D)(t,i),!p),y=O||I,C=ea(t,y),{isUploading:w,isTransferring:E,transferProgress:M}=Object(m.s)(t,o||v,p&&!y),S=!1===Object(He.a)(g),{shouldRender:k,transitionClassNames:N}=Object(Y.a)(E,void 0,S,"slow"),{shouldRenderThumb:P,shouldRenderFullMedia:T,transitionClassNames:A}=Object($t.a)(y,"slow"),x=Object(c.m)(()=>{w?u&&u(t):y?b&&b(t.id):f(e=>!e)},[y,w,t,u,b]),R=Object(m.sb)(t);Object(c.o)(()=>{if(!d)return;const e=h.current.closest(".message-content");y?ta(y,R,0,r).then(t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")}):e.classList.add("has-appendix-thumb")},[y,R,d,n,r]);const{width:L,height:F,isSmall:D}=l||Et(t),B=Object(K.a)("media-inner",!w&&"interactive",D&&"small-image",L===F&&"square-image"),U=Object(K.a)("thumbnail",!C&&"empty"),H=l?`width: ${L}px; height: ${F}px; left: ${l.x}px; top: ${l.y}px;`:"";return c.a.createElement("div",{id:e,ref:h,className:B,style:H,onClick:w?void 0:x},P&&c.a.createElement("img",{src:C,className:U,width:L,height:F,alt:""}),T&&c.a.createElement("img",{src:y,className:"full-media "+A,width:L,height:F,alt:""}),k&&c.a.createElement("div",{className:"media-loading "+N},c.a.createElement(aa.a,{progress:M,onClick:w?x:void 0})),!y&&!g&&c.a.createElement("i",{className:"icon-download"}),E&&c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*M),"%"))},na=a(123),ca=a(134);function ra(e,t){const a=Object(c.q)();a.current=t;const s=Object(c.m)(()=>{e.current&&e.current.pause()},[e]),n=Object(c.m)(()=>{e.current&&a.current&&Object(ca.a)(e.current)},[e]);Object(Q.a)(s,n)}var oa=a(137);function ia(){return(ia=Object.assign||function(e){for(var t=1;t{const b=Object(c.q)(null),u=Object(c.q)(null),h=t.content.video,O=h.blobUrl,j=Boolean(O)||Object(m.b)(h),g=Object(Ot.b)(b,a),[f,p]=Object(c.r)(s),I=Boolean(f&&g&&o),[v,y]=Object(c.r)(n),C=Object(Xe.a)(Object(m.D)(t,"pictogram"),!(g&&o),Object(m.C)(t,"pictogram"),o),w=ea(t,C),{mediaData:E,downloadProgress:M}=Object(Zt.a)(Object(m.D)(t,"inline"),!I,Object(m.C)(t,"inline"),o),S=C||w,k=O||E,N=Boolean(j&&g&&k),{isBuffered:P,bufferingHandlers:T}=Object(na.a)(!s),{isUploading:x,isTransferring:R,transferProgress:L}=Object(m.s)(t,r||M,I&&j&&!P),F=!1===Object(He.a)(f),{shouldRender:D,transitionClassNames:B}=Object(Y.a)(R,void 0,F),{shouldRenderThumb:U,transitionClassNames:H}=Object($t.a)(k,"slow"),[q,G]=Object(c.r)(0),_=Object(c.m)(e=>{G(Math.max(0,e.currentTarget.currentTime-1))},[]),z=Object(m.sb)(t),W=Object(m.pb)(t),{width:V,height:$}=i||Object(Je.h)(h,z,W);ra(u,N),Object(oa.a)(u,[N]);const Q=Object(c.m)(()=>{x?d&&d(t):j&&!k?p(e=>!e):j&&k&&!v?(y(!0),u.current.play()):l&&l(t.id)},[x,j,k,v,l,d,t]),J=Object(K.a)("media-inner dark",!x&&"interactive"),Z=Object(K.a)("thumbnail",!S&&"empty"),X=Object(K.a)("full-media",H),ee=S?`background-image: url(${S}); background-size: cover`:"",te=i?`width: ${V}px; height: ${$}px; left: ${i.x}px; top: ${i.y}px;`:"",ae=N,se=!j&&E,ne=!j||f&&!v&&!D,ce=j&&!f;return c.a.createElement("div",{ref:b,id:e,className:J,style:te,onClick:x?void 0:Q},(U||!N)&&c.a.createElement("img",{src:S,className:Z,width:V,height:$,alt:""}),ae&&c.a.createElement("video",ia({ref:u,className:X,width:V,height:$,autoPlay:v,muted:!0,loop:!0,playsInline:!0,style:ee},T,{onTimeUpdate:_}),c.a.createElement("source",{src:k})),se&&c.a.createElement("img",{src:E,className:"full-media "+H,width:V,height:$,alt:""}),ne&&c.a.createElement("i",{className:"icon-large-play"}),D&&c.a.createElement("div",{className:"media-loading "+B},c.a.createElement(aa.a,{progress:L,onClick:x?Q:void 0})),ce&&c.a.createElement("i",{className:"icon-download"}),R&&!j?c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*L),"%"):R&&j?c.a.createElement("span",{className:"message-upload-progress"},"..."):c.a.createElement("div",{className:"message-media-duration"},h.isGif?"GIF":Object(A.e)(h.duration-q)))},da=a(18);a(214);var ba=Object(s.h)((e,{contact:t})=>({user:Object(o.Db)(e,t.userId)}),(e,t)=>Object(d.l)(t,["openUserInfo"]))(({contact:e,user:t,openUserInfo:a})=>{const{firstName:s,lastName:n,phoneNumber:r,userId:o}=e,i=Object(c.m)(()=>{a({id:o})},[a,o]);return c.a.createElement("div",{className:Object(K.a)("Contact",Boolean(o)&&"interactive"),onClick:o?i:void 0},c.a.createElement(Bt.a,{size:"large",user:t,text:s||n}),c.a.createElement("div",{className:"contact-info"},c.a.createElement("div",{className:"contact-name"},s," ",n),c.a.createElement("div",{className:"contact-phone"},Object(da.c)(r))))}),ua=a(41);var ma=Object(c.h)(({id:e,options:t,selected:a=[],disabled:s,round:n,loadingOptions:r,onChange:o})=>{const[i,l]=Object(c.r)([]),d=Object(c.m)(e=>{const{value:t,checked:a}=e.currentTarget;let s;s=a?[...i,t]:i.filter(e=>e!==t),l(s),o(s)},[o,i]);return c.a.createElement("div",{id:e,className:"radio-group"},t.map(e=>c.a.createElement(ua.a,{label:e.label,subLabel:e.subLabel,value:e.value,checked:-1!==a.indexOf(e.value),disabled:s,round:n,isLoading:r?-1!==r.indexOf(e.value):void 0,onChange:d})))}),ha=a(117),Oa=a(170);a(217);function ja(e,t){return t>0?(e/t*100).toFixed():0}var ga=({answer:e,voteResults:t,totalVoters:a,maxVotersCount:s,correctResults:n,shouldAnimate:r})=>{const o=t&&t.find(t=>t.option===e.option),i=0===n.length||-1!==n.indexOf(e.option),l=n.length>0&&i||o&&o.isChosen,d=o?ja(o.votersCount,a||0):0,[b,u]=Object(c.r)(r?0:d),m=Object(c.q)(null),h=o?ja(o.votersCount,s||0):0,O=b{r&&u(d)},[r,d]),Object(c.n)(()=>{const e=m.current;if(e&&r){const t=e.firstElementChild,a=O?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",a):e.innerHTML=`\n \n \n `}},[O,r]),!t||!o)return;const j=`width: ${h}%; transform:scaleX(${O?0:1})`;return c.a.createElement("div",{className:"PollOption"},c.a.createElement("div",{className:"poll-option-share "+("100"===d?"limit-width":"")},d,"%",l&&c.a.createElement("span",{className:Object(K.a)("poll-option-chosen",!i&&"wrong",r&&"animate")},c.a.createElement("i",{className:i?"icon-check":"icon-close"}))),c.a.createElement("div",{className:"poll-option-right"},c.a.createElement("div",{className:"poll-option-text"},Object(Ze.a)(e.text)),c.a.createElement("div",{className:Object(K.a)("poll-option-answer",l&&!i&&"wrong")},c.a.createElement("div",{className:"poll-option-corner",ref:m}),c.a.createElement("div",{className:"poll-option-line",style:j}))))};a(218);var fa=Object(c.h)(Object(s.h)((e,{poll:t})=>{const{recentVoterIds:a}=t.results,{byId:s}=e.users;return a&&0!==a.length?{recentVoterIds:a,usersById:s}:{}},(e,t)=>Object(d.l)(t,["loadMessage","openPollResults"]))(({message:e,poll:t,recentVoterIds:a,usersById:s,loadMessage:n,onSendVote:r,openPollResults:o})=>{const{id:i,chatId:l}=e,{summary:d,results:b}=t,[u,m]=Object(c.r)(!1),[h,O]=Object(c.r)([]),[j,g]=Object(c.r)(!1),[f,p]=Object(c.r)(!1),[I,v]=Object(c.r)(!d.closed&&d.closeDate&&d.closeDate>0?Math.min(d.closeDate-Math.floor(Date.now()/1e3),d.closePeriod):0),y=Object(c.q)(null),{results:C,totalVoters:w}=b,E=C&&C.some(e=>e.isChosen),M=!d.closed&&!E,S=!M&&d.isPublic&&Number(b.totalVoters)>0,k=M&&d.multipleChoice,N=C?Math.max(...C.map(e=>e.votersCount)):w,P=C?C.reduce((e,t)=>(t.isCorrect&&e.push(t.option),e),[]):[],T=d.answers.map(e=>({label:e.text,value:e.option,hidden:Boolean(d.quiz&&d.closePeriod&&I<=0)}));Object(c.n)(()=>{u&&t.results.results&&t.results.results.some(e=>e.isChosen)&&m(!1)},[u,t.results.results]),Object(c.n)(()=>{I>0&&setTimeout(()=>v(I-1),1e3);const e=y.current;if(e){const t=12*Math.PI,a=e.lastElementChild,s=e.firstElementChild;if(I<=5&&e.classList.add("hurry-up"),a&&s){const e=(d.closePeriod-I)/d.closePeriod*t;s.textContent=Object(A.e)(I),a.firstElementChild.setAttribute("stroke-dashoffset","-"+e)}else e.innerHTML=`\n ${Object(A.e)(I)}\n \n \n `}},[I,d.closePeriod]),Object(c.n)(()=>{d.quiz&&(I<=0||E&&!d.closed)&&n({chatId:l,messageId:i})},[l,I,E,n,i,d.closed,d.quiz]),Object(c.n)(()=>{let e;return d.quiz&&!d.closed&&d.closePeriod&&d.closePeriod>0&&(e=window.setTimeout(()=>{n({chatId:l,messageId:i})},1e3*d.closePeriod)),()=>{e&&window.clearTimeout(e)}},[M,l,n,i,d.closePeriod,d.closed,d.quiz]);const x=Object(c.p)(()=>a?a.reduce((e,t)=>{const a=s[t];return a&&e.push(a),e},[]):[],[s,a]),R=Object(c.m)(e=>{O([e]),m(!0),p(!0),r([e])},[r]),L=Object(c.m)(e=>{O(e)},[]),F=Object(c.m)(()=>{m(!0),p(!0),r(h)},[r,h]),D=Object(c.m)(()=>{o({chatId:l,messageId:i})},[l,i,o]),B=Object(c.m)(()=>{g(!0)},[]),U=Object(c.m)(()=>{g(!1),p(!1)},[]);Object(c.n)(()=>{if(f&&E&&d.quiz&&b.results&&t.results.solution){b.results.find(e=>e.isChosen&&e.isCorrect)||g(!0)}},[E,f,b.results,d.quiz,t.results.solution]);const H=Object(te.a)();return c.a.createElement("div",{className:"Poll"},j&&t.results.solution&&c.a.createElement(Oa.a,{message:Object(yt.b)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:U}),c.a.createElement("div",{className:"poll-question"},Object(Ze.a)(d.question)),c.a.createElement("div",{className:"poll-type"},function(e){if(void 0===e.isPublic)return" ";if(e.quiz)return e.isPublic?"Quiz":"Anonymous Quiz";if(e.closed)return"Final results";return e.isPublic?"Poll":"Anonymous Poll"}(d),x.length>0&&c.a.createElement("div",{className:"poll-recent-voters"},x.map(e=>c.a.createElement(Bt.a,{size:"micro",user:e}))),I>0&&M&&c.a.createElement("div",{ref:y,className:"poll-countdown"}),d.quiz&&t.results.solution&&!M&&c.a.createElement(ne.a,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:j,onClick:B,ariaLabel:"Show Solution"},c.a.createElement("i",{className:"icon-lamp"}))),M&&c.a.createElement("div",{className:"poll-answers"},k?c.a.createElement(ma,{options:T,onChange:L,disabled:e.isScheduled||u,loadingOptions:u?h:void 0,round:!0}):c.a.createElement(ha.a,{name:"poll-"+i,options:T,onChange:R,disabled:e.isScheduled||u,loadingOption:u?h[0]:void 0})),!M&&c.a.createElement("div",{className:"poll-results"},d.answers.map((function(e){return c.a.createElement(ga,{key:e.option,shouldAnimate:f,answer:e,voteResults:C,totalVoters:w,maxVotersCount:N,correctResults:P})}))),!S&&!k&&c.a.createElement("div",{className:"poll-voters-count"},function(e,t){if(!t)return e?"No answers yet":"No voters yet";return e?t+" answered":t+" voted"}(d.quiz,b.totalVoters)),k&&c.a.createElement(ne.a,{isText:!0,disabled:0===h.length,size:"tiny",onClick:F},H("PollSubmitVotes")),S&&c.a.createElement(ne.a,{isText:!0,size:"tiny",onClick:D},H("PollViewResults")))})),pa=a(147),Ia=a(51);a(219);var va=Object(c.h)(({message:e,observeIntersection:t,shouldAutoLoad:a,inPreview:s,onMediaClick:n,onCancelMediaTransfer:r})=>{const o=Object(m.P)(e);let i=!1;if(o&&o.photo){const{width:t,height:a}=Et(e);i=t===a}const l=Object(c.m)(()=>{o&&(i||o.hasDocument)?window.open(o.url):n&&n()},[o,i,n]);if(!o)return;const{siteName:d,url:b,displayUrl:u,title:h,description:O,photo:j}=o,g=Object(pa.a)(O,170),f=Object(K.a)("WebPage",j?i&&"with-square-photo":!s&&"without-photo");return c.a.createElement("div",{className:f,"data-initial":(d||u)[0]},j&&c.a.createElement(sa,{message:e,observeIntersection:t,shouldAutoLoad:a,size:i?"pictogram":"inline",onClick:l,onCancelUpload:r}),c.a.createElement("div",{className:"WebPage-text"},c.a.createElement(Ia.a,{className:"site-name",url:b,text:d||u}),!s&&h&&c.a.createElement("p",{className:"site-title"},Object(Ze.a)(h)),g&&c.a.createElement("p",{className:"site-description"},Object(Ze.a)(g,["emoji","br"]))))});a(220);var ya=Object(c.h)(({message:e})=>{const t=Object(m.z)(e),{title:a,text:s,description:n,photoUrl:r}=t;return c.a.createElement("div",{className:"Invoice"},a&&c.a.createElement("p",{className:"title"},Object(Ze.a)(a)),s&&c.a.createElement("p",null,Object(Ze.a)(s,["emoji","br"])),c.a.createElement("div",{className:"description "+(r?"has-image":"")},r&&c.a.createElement("img",{className:"invoice-image",src:r,alt:""}),n&&c.a.createElement("p",{className:"description-text"},Object(Ze.a)(n,["emoji","br"]))))});function Ca(e){return Object(c.h)(Object(s.h)((e,t)=>{const{message:a}=t;return{isInSelectMode:Object(o.R)(e),isSelected:Object(o.U)(e,a.id)}},(e,t)=>Object(d.l)(t,["toggleMessageSelection"]))(t=>{const{isInSelectMode:a,isSelected:s,message:n,toggleMessageSelection:r,dimensions:o}=t,i=Object(c.m)(e=>{e.stopPropagation(),r({messageId:n.id,withShift:e&&e.shiftKey})},[r,n]),l=Object(c.p)(()=>({...t,isInSelectMode:a,isSelected:s,dimensions:{...t.dimensions,x:0,y:0},onClick:a?void 0:t.onClick}),[t,a,s]);return c.a.createElement("div",{className:Object(K.a)("album-item-select-wrapper",s&&"is-selected"),style:o?`left: ${o.x}px; top: ${o.y}px;`:"",onClick:a?i:void 0},a&&c.a.createElement("div",{className:"message-select-control"},s&&c.a.createElement("i",{className:"icon-select"})),c.a.createElement(e,l))}))}a(221);const wa=Ca(sa),Ea=Ca(la);var Ma=Object(s.h)(e=>({uploadsById:e.fileUploads.byMessageLocalId}),(e,t)=>Object(d.l)(t,["cancelSendingMessage"]))(({album:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,hasCustomAppendix:n,lastSyncTime:r,isOwn:o,albumLayout:i,onMediaClick:l,uploadsById:d,cancelSendingMessage:b})=>{const u=e.messages.length,h=Object(c.m)(e=>{b({chatId:e.chatId,messageId:e.id})},[b]);const{width:O,height:j}=i.containerStyle;return c.a.createElement("div",{className:"Album",style:`width: ${O}px; height: ${j}px;`},e.messages.map((function(e,b){const{photo:O,video:j}=Object(m.v)(e),g=d[e.previousLocalId||e.id],f=g?g.progress:void 0,{dimensions:p,sides:I}=i.layout[b];if(O){const s=n&&(o?b===u-1:Boolean(I&Pt&&I&Nt));return c.a.createElement(wa,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAffectAppendix:s,uploadProgress:f,dimensions:p,onClick:l,onCancelUpload:h})}if(j)return c.a.createElement(Ea,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,uploadProgress:f,lastSyncTime:r,dimensions:p,onClick:l,onCancelUpload:h})})))});a(222);function Sa(){return(Sa=Object.assign||function(e){for(var t=1;t{const r=Object(c.q)(null),o=Object(c.q)(null),i=Object(c.q)(null),l=e.content.video,d=Object(Ot.b)(r,t),[b,u]=Object(c.r)(a&&s),h=Boolean(b&&d&&n),{mediaData:O,downloadProgress:j}=Object(Zt.a)(Object(m.D)(e,"inline"),!h,Object(m.C)(e,"inline"),n),g=ea(e,O),{isBuffered:f,bufferingHandlers:p}=Object(na.a)(),I=b&&!f,v=!1===Object(He.a)(b),{shouldRender:y,transitionClassNames:C}=Object(Y.a)(I||!f,void 0,v),{shouldRenderThumb:w,transitionClassNames:E}=Object($t.a)(O,"slow"),[M,S]=Object(c.r)(!1),[k,N]=Object(c.r)(0);Object(c.n)(()=>{if(!M)return;const e=188*Math.PI,t=e-k*e,a=i.current,s=o.current,n=s.firstElementChild;n?n.firstElementChild.setAttribute("stroke-dashoffset",t.toString()):s.innerHTML=`\n \n `,N(a.currentTime/a.duration)},[M,k]);const P=Boolean(O&&d),T=()=>{S(!1),N(0),Object(ca.a)(i.current),requestAnimationFrame(()=>{o.current.innerHTML=""})},x=(R=T,()=>{ka&&ka(),ka=R});var R;Object(c.n)(()=>{i.current&&(P?Object(ca.a)(i.current):i.current.pause())},[P]),ra(i,P),Object(oa.a)(i,[O]);const L=Object(c.m)(()=>{if(!O)return void u(e=>!e);const e=i.current;M?e.paused?Object(ca.a)(e):e.pause():(e.currentTime=0,S(!0),x())},[x,M,O]),F=Object(c.m)(e=>{const t=e.currentTarget;N(t.currentTime/t.duration)},[]),D=Object(K.a)("full-media",E);return c.a.createElement("div",{ref:r,className:"RoundVideo media-inner",onClick:L},w&&c.a.createElement("div",{className:"thumbnail-wrapper"},c.a.createElement("img",{src:g,className:"thumbnail",width:Je.d,height:Je.d,alt:""})),O&&c.a.createElement("div",{className:"video-wrapper"},c.a.createElement("video",Sa({ref:i,className:D,width:Je.d,height:Je.d,autoPlay:!0,muted:!M,loop:!M,playsInline:!0,poster:g,onEnded:M?T:void 0},p,{onTimeUpdate:M?F:void 0}),c.a.createElement("source",{src:O}))),c.a.createElement("div",{className:"progress",ref:o}),y&&c.a.createElement("div",{className:"media-loading "+C},c.a.createElement(aa.a,{progress:j})),!O&&!b&&c.a.createElement("i",{className:"icon-large-play"}),c.a.createElement("div",{className:"message-media-duration"},M?Object(A.e)(i.current.currentTime):Object(A.e)(l.duration),(!M||i.current.paused)&&c.a.createElement("i",{className:"icon-muted-chat"})))};a(223);var Pa=({message:e,onClick:t})=>c.a.createElement("div",{className:"InlineButtons"},e.inlineButtons.map(e=>c.a.createElement("div",{className:"row"},e.map(e=>c.a.createElement(ne.a,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},e.text)))));a(224);var Ta=Object(c.h)(Object(s.h)((e,{message:t})=>{const{threadId:a,chatId:s}=t.threadInfo,n=Object(o.zb)(e,s,a)||t.threadInfo,{byId:c}=e.users,{byId:r}=e.chats;return{threadInfo:n,usersById:c,chatsById:r}},(e,t)=>Object(d.l)(t,["openChat"]))(({disabled:e,threadInfo:t,usersById:a,chatsById:s,openChat:n})=>{const{threadId:r,chatId:o,messagesCount:i,lastMessageId:l,lastReadInboxMessageId:d,recentReplierIds:b}=t,u=Object(c.m)(()=>{n({id:o,threadId:r})},[n,o,r]);if(void 0===i)return;const h=b&&b.map(e=>Object(m.kb)(e)?a[e]:s[e]).filter(Boolean);const O=Boolean(d&&l&&d0&&c.a.createElement("div",{className:"recent-repliers"},h.map(e=>c.a.createElement(Bt.a,{key:e.id,size:"small",user:Object(m.kb)(e.id)?e:void 0,chat:Object(m.kb)(e.id)?void 0:e}))),c.a.createElement("div",{className:"label"},function(e){if(0===e)return"Leave a Comment";if(1===e)return"1 Comment";return Object(Ve.a)(e)+" Comments"}(i)),c.a.createElement("i",{className:"icon-next"}))}));a(225);function Aa(e){const t=Ra(e.currentTarget);t&&t.setAttribute("data-is-document-group-hover","")}function xa(e){const t=Ra(e.currentTarget);t&&t.removeAttribute("data-is-document-group-hover")}function Ra(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}var La=Object(c.h)(Object(s.h)((e,t)=>{const{focusedMessage:a,forwardMessages:s,lastSyncTime:n}=e,{message:c,album:r,withSenderName:i,withAvatar:l,threadId:d,messageListType:b}=t,{id:u,chatId:h,viaBotId:O,replyToMessageId:j,isOutgoing:g}=c,f=Object(o.f)(e,h),p=Object(o.O)(e,h),I=f&&Object(m.ib)(f),v=!p&&Object(m.db)(c),y=i||l||v?Object(o.qb)(e,c):void 0,C=Object(o.J)(e,c),w=O?Object(o.Db)(e,O):void 0,E=d?Object(o.Bb)(e,h,d):void 0,M=c.id===E,S=j===E,k=j&&!S?Object(o.k)(e,h,j):void 0,N=k&&Object(o.qb)(e,k),P=Object(o.Cb)(e,c),T="thread"===b&&(r?r.messages.some(t=>Object(o.T)(e,t)):Object(o.T)(e,c)),{direction:A,noHighlight:x}=T&&a||{},R=s.messageIds&&s.messageIds.includes(u),{query:L}=Object(o.A)(e)||{},F=Object(m.K)(c);let D;return D=r&&r.messages?r.messages.every(({id:t})=>Object(o.U)(e,t)):Object(o.U)(e,u),{forceSenderName:v,sender:y,originSender:C,botSender:w,shouldHideReply:S,isThreadTop:M,replyMessage:k,replyMessageSender:N,...g&&{outgoingStatus:Object(o.cb)(e,c,"scheduled"===b)},..."number"==typeof P&&{uploadProgress:P},isFocused:T,...T&&{focusDirection:A,noFocusHighlight:x},isForwarding:R,isChatWithSelf:p,isChannel:I,lastSyncTime:n,highlight:L,isSingleEmoji:Boolean(F),animatedEmoji:F?Object(o.c)(e,F):void 0,isInSelectMode:Object(o.R)(e),isSelected:D,isGroupSelected:!!c.groupedId&&!c.isInAlbum&&Object(o.P)(e,h,c.groupedId),threadId:d,isPinnedList:"pinned"===b,shouldAutoLoadMedia:f?Object(o.rb)(e,c,f,y):void 0,shouldAutoPlayMedia:Object(o.sb)(e,c),shouldLoopStickers:Object(o.tb)(e)}},(e,t)=>Object(d.l)(t,["focusMessage","openMediaViewer","openAudioPlayer","cancelSendingMessage","openUserInfo","openChat","markMessagesRead","sendPollVote","toggleMessageSelection","setReplyingToId","openForwardMenu","clickInlineButton"]))(({message:e,observeIntersectionForBottom:t,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:s,album:n,withAvatar:r,withSenderName:o,noComments:d,appearanceOrder:b,isFirstInGroup:u,isLastInGroup:h,isFirstInDocumentGroup:O,isLastInDocumentGroup:j,isLastInList:g,forceSenderName:f,sender:p,originSender:I,botSender:v,isThreadTop:y,shouldHideReply:C,replyMessage:w,replyMessageSender:E,outgoingStatus:M,uploadProgress:S,isFocused:k,focusDirection:N,noFocusHighlight:P,isForwarding:T,isChatWithSelf:A,isChannel:x,lastSyncTime:R,highlight:L,animatedEmoji:F,isInSelectMode:D,isSelected:B,isGroupSelected:U,threadId:H,messageListType:q,isPinnedList:G,shouldAutoLoadMedia:_,shouldAutoPlayMedia:z,shouldLoopStickers:W,focusMessage:V,openMediaViewer:$,openAudioPlayer:Q,openUserInfo:J,openChat:Z,cancelSendingMessage:X,markMessagesRead:ee,sendPollVote:ae,toggleMessageSelection:se,setReplyingToId:ce,openForwardMenu:re,clickInlineButton:oe})=>{const ie=Object(c.q)(null),le=Object(c.q)(null),de=Object(c.q)(null);Object(Ot.c)(le,t);const{width:be}=Ue(),{isContextMenuOpen:ue,contextMenuPosition:me,handleBeforeContextMenu:he,handleContextMenu:Oe,handleContextMenuClose:je,handleContextMenuHide:ge}=Object(vt.a)(ie),fe=b<=0,[pe,Ie]=Object(nt.a)(fe);Object(c.n)(()=>{fe||setTimeout(Ie,10*b)},[b,Ie,fe]);const{transitionClassNames:ve}=Object(Y.a)(pe,void 0,fe,!1),{chatId:ye,id:Ce,threadInfo:we}=e,Ee=Object(m.sb)(e),Me="scheduled"===q||e.isScheduled,Se=Object(m.tb)(e)&&!C,ke=Boolean(we)&&"thread"===q,{forwardInfo:Ne,viaBotId:Pe}=e,Te=Ne&&!A&&!Ne.isLinkedChannelPost,Ae=!!e.groupedId&&!e.isInAlbum,xe=Boolean(n)&&n.messages.length>1,{text:Re,photo:Le,video:Fe,audio:De,voice:Be,document:He,sticker:qe,contact:Ge,poll:_e,webPage:We,invoice:Ve}=Object(m.v)(e),$e=Object(m.x)(e),Qe=Object(yt.a)(e,L,Ct($e)),Ke=void 0!==me,Ye=Object(K.a)("Message message-list-item",u&&"first-in-group",h&&"last-in-group",O&&"first-in-document-group",j&&"last-in-document-group",g&&"last-in-list",Ee&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Se&&"has-reply",Ke&&"has-menu-open",k&&!P&&"focused",T&&"is-forwarding",e.isDeleting&&"is-deleting",Ae&&"is-in-document-group",xe&&"is-album",e.hasUnreadMention&&"has-unread-mention",B&&"is-selected",D&&"is-in-selection-mode",y&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",ve),Xe=function(e,{hasReply:t,customShape:a,isLastInGroup:s,asForwarded:n,hasThread:c,forceSenderName:r,hasComments:o}={}){const{text:i,photo:l,video:d,audio:b,voice:u,document:h,poll:O,webPage:j,contact:g}=Object(m.v)(e),f=["message-content"],p=(l||d)&&!i,I=Boolean(e.viaBotId);return Ct(a)?f.push("emoji-only emoji-only-"+a):i&&f.push("text"),a&&(f.push("custom-shape"),d&&d.isRound&&f.push("round"),o&&f.push("has-comments")),l||d?f.push("media"):b?f.push("audio"):u?f.push("voice"):h?f.push("document"):g?f.push("contact"):O?f.push("poll"):j&&(f.push("web-page"),j.photo&&f.push("media")),n&&!a&&f.push("is-forwarded"),t&&f.push("is-reply"),c&&f.push("has-replies"),I&&f.push("is-via-bot"),r&&f.push("force-sender-name"),a||(f.push("has-shadow"),(t||n||!p||I||r)&&f.push("has-solid-background"),!s||!l&&p||f.push("has-appendix")),f.join(" ")}(e,{hasReply:Se,customShape:$e,isLastInGroup:h,asForwarded:Te,hasThread:ke,forceSenderName:f,hasComments:e.threadInfo&&e.threadInfo.messagesCount>0}),et=!Ne||!A&&p?p:I,tt=Ne?I:p,at=x&&e.adminTitle||Ne&&!Te&&Ne.adminTitle||void 0;Object(ze.a)(ye,Se?e.replyToMessageId:void 0,w,e.id),Dt(ie,ye,k,N,P),Object(c.o)(()=>{de.current&&(de.current.innerHTML=Ee?'':'')},[Ee]);const st=Object(c.m)(t=>{t.stopPropagation(),se({messageId:Ce,groupedId:e.groupedId})},[Ce,e.groupedId,se]),ct=Object(c.m)(e=>{const t=xe&&n&&n.messages?{messageId:Ce,childMessageIds:n.messages.map(({id:e})=>e),withShift:e&&e.shiftKey}:{messageId:Ce,withShift:e&&e.shiftKey};se(t)},[se,Ce,xe,n]),rt=Object(c.m)(()=>{ce({messageId:Ce})},[ce,Ce]),ot=Object(c.m)(e=>{e.stopPropagation()},[]),it=Object(c.m)(()=>{et&&(Object(m.kb)(et.id)?J({id:et.id}):Z({id:et.id}))},[et,J,Z]),lt=Object(c.m)(()=>{tt&&(Object(m.kb)(tt.id)?J({id:tt.id}):Z({id:tt.id}))},[tt,J,Z]),dt=Object(c.m)(()=>{v&&J({id:v.id})},[v,J]),bt=Object(c.m)(()=>{V({chatId:ye,threadId:H,messageId:e.replyToMessageId})},[V,ye,H,e.replyToMessageId]),ut=Object(c.m)(()=>{$({chatId:ye,threadId:H,messageId:Ce,origin:Me?l.h.ScheduledInline:l.h.Inline})},[ye,H,Ce,$,Me]),mt=Object(c.m)(()=>{Q({chatId:ye,messageId:Ce})},[ye,Ce,Q]),ht=Object(c.m)(e=>{$({chatId:ye,threadId:H,messageId:e,origin:Me?l.h.ScheduledAlbum:l.h.Album})},[ye,H,$,Me]),jt=Object(c.m)(()=>{ee({messageIds:[Ce]})},[Ce,ee]),gt=Object(c.m)(()=>{X({chatId:ye,messageId:Ce})},[X,ye,Ce]),ft=Object(c.m)(e=>{ae({chatId:ye,messageId:Ce,options:e})},[ye,Ce,ae]),pt=Object(c.m)(()=>{re({fromChatId:ye,groupedId:e.groupedId})},[re,ye,e.groupedId]),It=Object(c.m)(()=>{if(n&&n.messages){const e=n.messages.map(({id:e})=>e);re({fromChatId:ye,messageIds:e})}else re({fromChatId:ye,messageIds:[Ce]})},[n,re,ye,Ce]),Mt=Object(c.m)(()=>{V({chatId:ye,threadId:i.MAIN_THREAD_ID,messageId:Ce})},[V,ye,Ce]),St=Object(c.m)(()=>{V(Ae?{chatId:Ne.fromChatId,groupedId:e.groupedId,groupedChatId:ye}:{chatId:Ne.fromChatId,messageId:Ne.fromMessageId})},[V,Ne,e,ye,Ae]),kt=Object(te.a)();let Nt,Pt="";const Tt=Object(c.p)(()=>xe?Rt(Ee,Boolean(Te),n,be):void 0,[xe,be,Ee,Te,n]),At=Te?28:0;if(xe||!Le&&!Fe)Tt&&(Nt=Math.max(wt(Boolean(Re)),Tt.containerStyle.width));else{let t;Le?t=Et(e).width:Fe&&(t=Fe.isRound?Je.d:Et(e).width),t&&(Nt=Math.max(wt(Boolean(Re)),t))}Nt&&(Pt=`width: ${Nt+At}px`);const xt=Object(c.p)(()=>at?Ft(at):void 0,[at]),Lt=!(Ke||D||T)&&(!Ae||j),Ut=Lt&&x&&!Me,qt=Lt&&(Ne&&(Ne.isChannelPost||A&&!Ee)&&Ne.fromMessageId||G),Wt=e.threadInfo&&(!Ae||j)&&"thread"===q&&!d;return c.a.createElement("div",{ref:ie,id:"message"+Ce,className:Ye,style:xt?`--meta-safe-author-width: ${xt}px`:void 0,"data-message-id":Ce,onClick:D?ct:void 0,onDoubleClick:D?void 0:rt,onMouseDown:D?void 0:he,onContextMenu:D?void 0:Oe,onMouseEnter:Ae&&!j?Aa:void 0,onMouseLeave:Ae&&!j?xa:void 0},c.a.createElement("div",{ref:le,className:"bottom-marker","data-message-id":Ce,"data-last-message-id":n?n.messages[n.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!Ae&&c.a.createElement("div",{className:"message-select-control"},B&&c.a.createElement("i",{className:"icon-select"})),j&&c.a.createElement("div",{className:Object(K.a)("message-select-control group-select",U&&"is-selected"),onClick:st},U&&c.a.createElement("i",{className:"icon-select"})),r&&function(){const e=et&&Object(m.kb)(et.id),t=et&&e?et:void 0,a=et&&!e?et:void 0,s=!et&&Ne?Ne.hiddenUserName:void 0;return c.a.createElement(Bt.a,{size:"small",user:t,chat:a,text:s,lastSyncTime:R,onClick:t||a?it:void 0})}(),c.a.createElement("div",{className:"message-content-wrapper",onClick:D&&Ae?ct:void 0},c.a.createElement("div",{className:Xe,style:Pt},Xe.includes("has-appendix")&&c.a.createElement("div",{className:"svg-appendix",ref:de}),Te&&!$e&&(!Ae||O)&&c.a.createElement("div",{className:"message-title"},kt("ForwardedMessage")),function(){const t=Object(K.a)("content-inner",Te&&!$e&&"forwarded-message",Se&&"reply-message"),r=h&&!Qe&&!Te&&!ke;return c.a.createElement("div",{className:t,onDoubleClick:ot},function(){if($e||!(o&&!Le&&!Fe||Te||Pe||f)||Ae&&!O)return;let t,a;tt?(t=Object(m.U)(tt),Te||(a="color-"+Object(m.W)(tt))):Ne&&Ne.hiddenUserName&&(t=Ne.hiddenUserName);return c.a.createElement("div",{className:"message-title"},t?c.a.createElement("span",{className:Object(K.a)(tt&&"interactive",a),onClick:tt?lt:void 0},Object(Ze.a)(t)):v?void 0:" ",v&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"via"},kt("ViaBot")),c.a.createElement("span",{className:"interactive",onClick:dt},Object(Ze.a)("@"+v.username))),Ne&&Ne.isLinkedChannelPost?c.a.createElement("span",{className:"admin-title"},kt("DiscussChannel")):e.adminTitle&&!x?c.a.createElement("span",{className:"admin-title"},e.adminTitle):void 0)}(),Se&&c.a.createElement(Gt,{message:w,sender:E,observeIntersection:a,onClick:bt}),qe&&c.a.createElement(Yt,{message:e,observeIntersection:a,observeIntersectionForPlaying:s,shouldLoop:W,lastSyncTime:R}),F&&c.a.createElement(Jt.a,{isInline:!0,sticker:F,observeIntersection:a,lastSyncTime:R}),xe&&c.a.createElement(Ma,{album:n,albumLayout:Tt,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,isOwn:Ee,hasCustomAppendix:r,lastSyncTime:R,onMediaClick:ht}),!xe&&Le&&c.a.createElement(sa,{message:e,observeIntersection:a,shouldAutoLoad:_,uploadProgress:S,shouldAffectAppendix:r,onClick:ut,onCancelUpload:gt}),!xe&&Fe&&Fe.isRound&&c.a.createElement(Na,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,lastSyncTime:R}),!xe&&Fe&&!Fe.isRound&&c.a.createElement(la,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,uploadProgress:S,lastSyncTime:R,onClick:ut,onCancelUpload:gt}),(De||Be)&&c.a.createElement(zt.a,{message:e,uploadProgress:S,lastSyncTime:R,isSelectable:Ae,isSelected:B,onPlay:mt,onReadMedia:!Be||Ee&&!A?void 0:jt,onCancelUpload:gt}),He&&c.a.createElement(_t.a,{message:e,observeIntersection:a,uploadProgress:S,isSelectable:Ae,isSelected:B,onCancelUpload:gt}),Ge&&c.a.createElement(ba,{contact:Ge}),_e&&c.a.createElement(fa,{message:e,poll:_e,onSendVote:ft}),!F&&Qe&&c.a.createElement("p",{className:"text-content"},Qe),We&&c.a.createElement(va,{message:e,observeIntersection:a,shouldAutoLoad:_,onMediaClick:ut,onCancelMediaTransfer:gt}),Ve&&c.a.createElement(ya,{message:e}))}(),(!Ae||j)&&c.a.createElement(Vt,{message:e,outgoingStatus:M,signature:at,onClick:ct}),Ut?c.a.createElement(ne.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Forward message",onClick:j?pt:It},c.a.createElement("i",{className:"icon-share-filled"})):qt?c.a.createElement(ne.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:G?Mt:St},c.a.createElement("i",{className:"icon-arrow-right"})):void 0,Wt&&c.a.createElement(Ta,{message:e,disabled:d})),e.inlineButtons&&c.a.createElement(Pa,{message:e,onClick:oe})),me&&c.a.createElement(Ht,{isOpen:ue,anchor:me,message:e,album:n,messageListType:q,onClose:je,onCloseAnimationEnd:ge}))}));a(226);const Fa=h.b?1e3:350,Da=h.f?300:500,Ba=Object(g.a)(e=>e(),200,!1),Ua=Object(g.j)(e=>e());var Ha=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,type:s})=>{const n=Object(o.f)(e,t);if(!n)return{};const c=Object(o.x)(e,t,a,s),r="scheduled"===s?Object(o.nb)(e,t):Object(o.m)(e,t),l=Object(o.Bb)(e,t,a);if(a!==i.MAIN_THREAD_ID&&!(r&&l&&r[l]))return{};const{isRestricted:d,restrictionReason:b,lastMessage:u}=n,h=Object(o.H)(e,t),O=a===i.MAIN_THREAD_ID&&!c&&!n.unreadCount&&!h&&u&&!u.groupedId;let j;if(Object(o.K)(e,t)){const a=Object(o.g)(e,t);j=a.fullInfo?a.fullInfo.botDescription||"NoMessages":"Updating bot info..."}return{isChatLoaded:!0,isRestricted:d,restrictionReason:b,isChannelChat:Object(m.ib)(n),canPost:Object(m.e)(n,a),isChatWithSelf:Object(o.O)(e,t),messageIds:c,messagesById:r,firstUnreadId:Object(o.G)(e,t,a),isViewportNewest:"thread"!==s||Object(o.W)(e,t,a),threadFirstMessageId:Object(o.F)(e,t,a),focusingId:h,isSelectModeActive:Object(o.R)(e),animationLevel:e.settings.byKey.animationLevel,...O&&{lastMessage:u},botDescription:j,threadTopMessageId:l,hasLinkedChat:n.fullInfo&&"linkedChatId"in n.fullInfo?Boolean(n.fullInfo.linkedChatId):void 0}},(e,t)=>Object(d.l)(t,["loadViewportMessages","markMessageListRead","markMessagesRead","setScrollOffset"]))(({chatId:e,threadId:t,type:a,hasTools:r,onFabToggle:i,isChatLoaded:b,isChannelChat:u,canPost:O,bottomOffset:j,isChatWithSelf:f,messageIds:p,messagesById:I,firstUnreadId:v,isViewportNewest:y,threadFirstMessageId:C,isRestricted:w,restrictionReason:E,focusingId:M,isSelectModeActive:S,animationLevel:k,loadViewportMessages:N,markMessageListRead:P,markMessagesRead:T,setScrollOffset:x,lastMessage:R,botDescription:L,threadTopMessageId:F,hasLinkedChat:D})=>{const B=Object(c.q)(null),U=Object(c.q)("thread"===a&&Object(o.ob)(Object(s.e)(),e,t)||0),H=Object(c.q)(),q=Object(c.q)(),G=Object(c.q)(),_=Object(c.q)(v),z=Object(c.q)(),W=Object(c.q)(),V=Object(c.q)(!1),$=Object(c.q)(!p),[Y,J]=Object(c.r)(),[Z,X]=Object(c.r)(Boolean(M)),ee=Boolean(p);Object(me.a)(()=>{ee&&Object(g.d)(()=>{$.current=!1})},[ee]),Object(me.a)(()=>{z.current=v},[v]);const{observe:ae,freeze:se,unfreeze:ne}=Object(Ot.a)({rootRef:B,throttleMs:Fa,margin:Da}),{observe:ce,freeze:re,unfreeze:oe}=Object(Ot.a)({rootRef:B},e=>{if("thread"!==a)return;let t=0;const s=[];e.forEach(e=>{const{isIntersecting:a,target:n}=e;if(!a)return;const{dataset:c}=n,r=Number(c.lastMessageId||c.messageId);r>t&&(t=r),c.hasUnreadMention&&s.push(r)}),z.current&&t>=z.current&&P({maxId:t}),s.length&&T({messageIds:s})});Object(me.a)(()=>{W.current=M,M?(se(),re()):(oe(),ne())},[M]);const{observe:ie}=Object(Ot.a)({rootRef:B,throttleMs:Fa});Object(c.n)(()=>{M?X(!0):setTimeout(()=>{X(!1)},200)},[M]);const le=Object(c.p)(()=>{if(!p||!I)return;const e=!F||p[0]&&C!==p[0]?p:[F,...p];if(!e.length)return;const t=e.map(e=>I[e]);return ht(Object(d.k)(t,["date","id"]),_.current)},[p,I,C,F]),[de,be,ue]=Object(c.p)(()=>"thread"===a?[Object(g.a)(()=>N({direction:l.e.Backwards}),1e3,!0,!1),Object(g.a)(()=>N({direction:l.e.Forwards}),1e3,!0,!1),Object(g.a)(()=>N({direction:l.e.Around}),1e3,!0,!1)]:[],[N,p]),{isScrolled:he,updateStickyDates:Oe}=jt(),je=Object(c.m)(()=>{if(V.current)return void(V.current=!1);const s=B.current;W.current||Oe(s,r),Ba(()=>{Object(g.b)(()=>{s.parentElement&&(U.current=s.scrollHeight-s.scrollTop,"thread"===a&&x({chatId:e,threadId:t,scrollOffset:U.current}))})})},[Oe,r,a,x,e,t]);Object(c.n)(()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver(([e])=>{e.target.offsetParent&&J(e.contentRect.height)});return e.observe(B.current),()=>{e.disconnect()}},[]),Object(c.o)(()=>{B.current.dataset.normalHeight=String(B.current.offsetHeight)},[]),Object(c.o)(()=>{h.d&&Ua(()=>{if(!B.current.querySelector(".AnimatedSticker.is-playing"))return;const e=B.current.style;e.webkitOverflowScrolling="auto"===e.webkitOverflowScrolling?"":"auto"})}),Object(c.n)(()=>{if(!ue||!b||w||M)return;const e=B.current;(!p||p.length{const s=B.current;if(G.current=Array.from(s.querySelectorAll(".message-list-item")),!s.offsetParent)return;const c=y&&p&&p.length{s.parentElement&&s.parentElement.classList.remove("force-messages-scroll")},1e3));const{scrollTop:o,scrollHeight:i,offsetHeight:l}=s,d=U.current,b=G.current[G.current.length-1],u=b?b.offsetHeight:0,m=y&&t&&d-(a||l)-u<=100;let h;const O=p&&e&&p[0]!==e[0],j=p&&e&&p[p.length-1]!==e[e.length-1];if(m&&j&&!O&&!W.current&&(b&&Object(g.b)(()=>{Object(ft.a)(s,b,"end",20,void 0,void 0,void 0,!0)}),h=i-l,U.current=Math.max(i-h,l),!c))return;const f=void 0!==a&&a!==Y,I=H.current&&s.querySelector("#"+H.current),v=!I&&_.current&&s.querySelector(".unread-divider");if(m&&f){if(Object(ft.b)())return;h=i-l}else if(I){h=o+(I.getBoundingClientRect().top-(q.current||0))}else h=v?v.offsetTop-(r?60:10):i-d;Object(gt.a)(s,h),W.current||(V.current=!0,Object(g.b)(()=>{V.current=!1})),U.current=Math.max(i-h,l)},[p,y,Y,r]),Object(c.n)(()=>{(!k||k>0)&&Object(Q.b)(200+n.c)},[k,S]);const ge=Object(te.a)(),fe=Boolean(e&&Object(m.kb)(e)),pe=Boolean(!fe&&!u||f),Ie=Object(K.a)("MessageList custom-scroll",!pe&&"no-avatars",u&&"no-avatars",(!O||"none"!==j)&&"bottom-padding","none"!==j&&"bottom-padding-"+j,S&&"select-mode-active",Z&&"has-focusing",he&&"scrolled");return c.a.createElement("div",{ref:B,className:Ie,onScroll:je},w?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,E?E.text:"This is a private "+(u?"channel":"chat"))):L?c.a.createElement("div",{className:"empty rich"},c.a.createElement("span",null,Object(Ze.a)(ge(L),["br","emoji","links"]))):p&&!le?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,ge("NoMessages"))):p&&le||R?c.a.createElement(It,{containerRef:B,className:"messages-container",messageIds:p||[R.id],containerHeight:Y,listItemElementsRef:G,focusingId:M,anchorIdRef:H,anchorTopRef:q,loadMoreForwards:be,loadMoreBackwards:de,isViewportNewest:y,firstUnreadId:v,onFabToggle:i},function(e,t,a,s,r,o,i,l,b,u,h,O,j,g=!1,f=!1){const p=c.a.createElement("div",{className:Object(K.a)("unread-divider","local-action-message"),key:"unread-messages"},c.a.createElement("span",null,e("UnreadMessages"))),I=f?0:t.reduce((e,t)=>e+Object(d.h)(t.senderGroups).length,0);let v=0;const y=t.map((t,f,y)=>{const C=t.senderGroups.map((t,n,g)=>{if(1===t.length&&!mt(t[0])&&Object(m.cb)(t[0])){const e=t[0];return Object(d.e)([e.id===l.current&&p,c.a.createElement(qt,{key:e.id,message:e,observeIntersection:a,appearanceOrder:I-++v})])}let C;return Object(d.h)(t.map((w,E)=>{const M=mt(w)?w.mainMessage:w,S=mt(w)?w:void 0,k=Object(m.sb)(M),N=mt(w),P=t[E+1];M.previousLocalId&&i.current==="message"+M.previousLocalId&&(i.current="message"+M.id);const T=!N&&M.groupedId?M.groupedId:void 0,A=P&&!mt(P)?P.groupedId:void 0,x={isFirstInGroup:0===E,isLastInGroup:E===t.length-1,isFirstInDocumentGroup:Boolean(T&&T!==C),isLastInDocumentGroup:Boolean(T&&T!==A),isLastInList:E===t.length-1&&n===g.length-1&&f===y.length-1};C=T;const R=M.id===l.current&&l.current!==O||M.id===h&&l.current===O,L=Object(m.F)(M),F="scheduled"!==u?L:`${M.date}_${L}`;return Object(d.e)([R&&p,c.a.createElement(La,{key:F,message:M,observeIntersectionForBottom:a,observeIntersectionForMedia:s,observeIntersectionForAnimatedStickers:r,album:S,withAvatar:x.isLastInGroup&&o&&!k&&!(M.id===h),withSenderName:x.isFirstInGroup&&o&&!k,threadId:b,messageListType:u,noComments:!1===j,appearanceOrder:I-++v,isFirstInGroup:x.isFirstInGroup,isLastInGroup:x.isLastInGroup,isFirstInDocumentGroup:x.isFirstInDocumentGroup,isLastInDocumentGroup:x.isLastInDocumentGroup,isLastInList:x.isLastInList}),M.id===h&&c.a.createElement("div",{className:"local-action-message",key:"discussion-started"},c.a.createElement("span",null,e("DiscussionStarted")))])}))});return c.a.createElement("div",{className:"message-date-group",key:t.datetime,teactFastList:!0},c.a.createElement("div",{className:"sticky-date",key:"date-header"},c.a.createElement("span",null,g&&t.originalDate===n.kb&&e("MessageScheduledUntilOnline"),g&&t.originalDate!==n.kb&&e("MessageScheduledOn",Object(A.c)(t.datetime,void 0,!0)),!g&&Object(A.c)(t.datetime))),Object(d.h)(C))});return Object(d.h)(y)}(ge,le||ht([R]),ce,ae,ie,pe,H,_,t,a,F,C,D,!!le&&"scheduled"===a,!le||!$.current)):c.a.createElement(ve.a,{color:"white"}))}));a(227);var qa=Object(c.h)(Object(s.h)(e=>{const t=Object(o.y)(e);if(!t)return{};const{chatId:a,threadId:s,type:n}=t,c=Object(o.f)(e,a);return{messageListType:n,canPost:c&&Object(m.e)(c,s),unreadCount:c&&s===i.MAIN_THREAD_ID&&"thread"===n?c.unreadCount:void 0}},(e,t)=>Object(d.l)(t,["focusLastMessage"]))(({isShown:e,messageListType:t,canPost:a,unreadCount:s,focusLastMessage:n})=>{const r=Object(c.q)(null),o=Object(c.m)(()=>{if(e)if("thread"===t)n();else{const e=r.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),a=t[t.length-1];if(!a)return;Object(ft.a)(e,a,"end",20)}},[e,t,n]),i=Object(K.a)("ScrollDownButton",e&&"revealed",!a&&"no-composer");return c.a.createElement("div",{ref:r,className:i},c.a.createElement("div",{className:"ScrollDownButton-inner"},c.a.createElement(ne.a,{color:"secondary",round:!0,onClick:o,ariaLabel:"Scroll to bottom"},c.a.createElement("i",{className:"icon-arrow-down"})),Boolean(s)&&c.a.createElement("div",{className:"unread-count"},Object(Ve.b)(s))))})),Ga=a(124),_a=a(125),za=a(14);async function Wa(e,t,a,s){const n=URL.createObjectURL(t),{type:c,size:r}=t;let o,i;if(c.startsWith("image/"))if(a){const a=await Object(za.g)(n),{width:r,height:i}=a;if(r>1280||i>1280||"image/jpeg"!==c){const c=await function(e){return new Promise(t=>{const a=document.createElement("canvas"),s=a.getContext("2d");let{width:n,height:c}=e;(n>1280||c>1280)&&(n>=c?(c*=1280/n,n=1280):(n*=1280/c,c=1280)),a.width=n,a.height=c,s.drawImage(e,0,0,e.width,e.height,0,0,n,c),a.toBlob(t,"image/jpeg",100)})}(a);return c?(URL.revokeObjectURL(n),Wa(e,c,!0,s)):Wa(e,t,!1,s)}o={width:r,height:i}}else i=n;else if(c.startsWith("video/")){if(r<10485760){const{videoWidth:e,videoHeight:t,duration:a}=await Object(za.h)(n);o={width:e,height:t,duration:a}}i=await Object(za.c)(n)}return{blobUrl:n,filename:e,mimeType:c,size:r,quick:o,previewBlobUrl:i,...s}}var Va=a(171),$a=a.p+"8ccc0b555efcec3616377aea078dda16.js";const Qa={encoderPath:$a,reuseWorker:!0},Ka={type:"audio/ogg"};let Ya,Ja,Za;async function Xa(){return Ya||(Ya=a.e(9).then(a.t.bind(null,305,7)),Ja=(await Ya).default,Za=new Ja(Qa)),Ya}async function es(e){await async function(){await Xa(),await Za.start()}();const t=Date.now();let a;const s=[],n=[];Za.ondataavailable=e=>{s.push(e)};const c=function(e,t){const a=e.sourceNode,s=a.context.createAnalyser();s.fftSize=64,a.connect(s);const n=s.frequencyBinCount,c=new Uint8Array(n);let r=!1;return function e(){if(r)return;s.getByteFrequencyData(c);const a=c.reduce((e,t)=>e+t,0),o=a/n/255;t(o<.1?0:o),requestAnimationFrame(e)}(),()=>{r=!0}}(Za,t=>{n.push(255*t),e(t)});return{stop:()=>new Promise((e,r)=>{Za.onstop=()=>{e({blob:new Blob(s,Ka),duration:Math.round(((a||Date.now())-t)/1e3),waveform:n})},Za.onerror=r;const o=Math.max(0,t+1e3-Date.now());setTimeout(()=>{Za.stop(),c()},o)}),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout(()=>{Za.pause(),a=Date.now(),c()},e)}}}const ts=["image/png","image/jpeg","image/gif"];function as(e){const{text:t,entities:a}=e||{};if(!t)return"";const s=Object(yt.b)(t,a,void 0,void 0,!0);return Array.isArray(s)?s.join(""):s}let ss,ns;var cs=a(58);var rs=a(180);var os=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"DeleteMessageModal",!t);return a?c.a.createElement(a,e):void 0};function is(){return(is=Object.assign||function(e){for(var t=1;t{const a=Object(c.q)(!1),s=Object(c.m)(()=>{if(a.current=!0,ds)return ds=!1,void e();ls&&(clearTimeout(ls),ls=void 0),ls=window.setTimeout(()=>{a.current&&e()},200)},[e]),n=Object(c.m)(()=>{a.current=!1},[]);return c.a.createElement(ne.a,is({},t,{onMouseEnter:h.k?void 0:s,onMouseLeave:h.k?void 0:n,onClick:h.k?e:void 0}))});var us=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"AttachMenu",!t);return a?c.a.createElement(a,e):void 0};var ms=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"SymbolMenu",!t);return a?c.a.createElement(a,e):void 0};var hs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"MentionMenu",!t);return a?c.a.createElement(a,e):void 0};var Os=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"CustomSendMenu",!t);return a?c.a.createElement(a,e):void 0};var js=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"EmojiTooltip",!t);return a?c.a.createElement(a,e):void 0};var gs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"BotKeyboardMenu",!t);return a?c.a.createElement(a,e):void 0},fs=a(172),ps=a(109);a(229);var Is=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a,type:s}=Object(o.y)(e)||{};if(!t||!a||!s)return{};const{currentUserId:n,forwardMessages:{fromChatId:c,toChatId:r,messageIds:i}}=e,l=Object(o.jb)(e,t,a),d="scheduled"===s?Object(o.E)(e,t):Object(o.C)(e,t,a),b=e.settings.byKey.animationLevel>=1,u=r===t;let h,O;if(l?h=Object(o.k)(e,t,l):d?h=Object(o.D)(e,t,a,s):u&&1===i.length&&(h=Object(o.k)(e,c,i[0])),l&&h){const{forwardInfo:a}=h,s=t===n;a&&(a.isChannelPost||s)&&(O=Object(o.J)(e,h)),O||(O=Object(o.qb)(e,h))}else u&&(O=Object(m.kb)(c)?Object(o.Db)(e,c):Object(o.f)(e,c));return{replyingToId:l,editingId:d,message:h,sender:O,shouldAnimate:b,forwardedMessagesCount:u?i.length:void 0}},(e,t)=>Object(d.l)(t,["setReplyingToId","setEditingId","focusMessage","exitForwardMode"]))(({replyingToId:e,editingId:t,message:a,sender:s,shouldAnimate:n,forwardedMessagesCount:r,setReplyingToId:o,setEditingId:i,focusMessage:l,exitForwardMode:d})=>{const b=Boolean((e||t)&&a||s&&r),u=Object(ps.a)([r],r?300:void 0),{shouldRender:m,transitionClassNames:h}=Object(Y.a)(u&&b,void 0,!n,void 0,!n),O=Object(c.m)(()=>{e?o({messageId:void 0}):t?i({messageId:void 0}):r&&d()},[e,t,r,o,i,d]);Object(c.n)(()=>b?Object(Z.a)(O):void 0,[b,O]);const j=Object(c.m)(()=>{l({chatId:a.chatId,messageId:a.id})},[l,a]),g=Object(K.a)("ComposerEmbeddedMessage",h),f=r&&r>1?r+" forwarded messages":void 0;if(m)return c.a.createElement("div",{className:g},c.a.createElement("div",null,c.a.createElement(ne.a,{round:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:O},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(Gt,{className:"inside-input",message:a,sender:s,customText:f,title:t?"Edit Message":void 0,onClick:j})))}));var vs=e=>{const{attachments:t}=e,a=Object(Ie.a)(pe.a.Extra,"AttachmentModal",!t.length);return a?c.a.createElement(a,e):void 0};var ys=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"PollModal",!t);return a?c.a.createElement(a,e):void 0};var Cs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"DropArea",!t);return a?c.a.createElement(a,e):void 0};a(230);const ws=new RegExp(n.fb,"i");var Es=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a})=>{const s=Object(o.bb)(e,t,a);return{webPagePreview:e.webPagePreview,noWebPage:s}},(e,t)=>Object(d.l)(t,["loadWebPagePreview","clearWebPagePreview","toggleMessageWebPage"]))(({chatId:e,threadId:t,messageText:a,disabled:s,webPagePreview:n,noWebPage:r,loadWebPagePreview:o,clearWebPagePreview:l,toggleMessageWebPage:d})=>{const b=Object(c.p)(()=>{const{text:e,entities:t}=Object(_a.a)(a),s=t&&t.find(({type:e})=>e===i.ApiMessageEntityTypes.TextUrl);if(s)return s.url;const n=e.match(ws);return n?n[0]:void 0},[a]);Object(c.n)(()=>{b?o({text:b}):(l(),d({chatId:e,threadId:t}))},[e,d,l,b,o,t]),Object(me.a)(()=>{l(),d({chatId:e,threadId:t})},[e]);const u=Boolean(n&&a.length&&!r&&!s),{shouldRender:m,transitionClassNames:h}=Object(Y.a)(u),O=qe(n);if(!m||!O)return;const{photo:j,...g}=O,f={content:{webPage:g}};return c.a.createElement("div",{className:Object(K.a)("WebPagePreview",h)},c.a.createElement("div",null,c.a.createElement(ne.a,{round:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{d({chatId:e,threadId:t,noWebPage:!0})}},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(va,{message:f,inPreview:!0})))})),Ms=a(113);var Ss=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"CalendarModal",!t);return a?c.a.createElement(a,e):void 0};var ks=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"PaymentModal",!t);return a?c.a.createElement(a,e):void 0};var Ns,Ps=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ReceiptModal",!t);return a?c.a.createElement(a,e):void 0};a(231);!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(Ns||(Ns={}));var Ts=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=n&&Object(o.o)(e,n),r=n?Object(o.N)(e,n):void 0,l=Object(o.O)(e,t),d=r&&Object(o.ab)(e,t),b=Object(o.lb)(e,t);return{editingMessage:Object(o.D)(e,t,a,s),connectionState:e.connectionState,draft:Object(o.B)(e,t,a),chat:n,isChatWithBot:r,isChatWithSelf:l,canScheduleUntilOnline:!l&&!r&&n&&c&&Object(m.kb)(t)&&c.status&&Boolean(c.status.wasOnline),isRightColumnShown:Object(o.V)(e),isSelectModeActive:Object(o.R)(e),withScheduledButton:a===i.MAIN_THREAD_ID&&"thread"===s&&Boolean(b&&b.length),shouldSchedule:"scheduled"===s,botKeyboardMessageId:d?d.id:void 0,isForwarding:t===e.forwardMessages.toChatId,canSuggestMembers:n&&Object(m.jb)(n),isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:n&&n.fullInfo&&n.fullInfo.members,currentUserId:e.currentUserId,usersById:e.users.byId,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),shouldSuggestStickers:e.settings.byKey.shouldSuggestStickers}},(e,t)=>Object(d.l)(t,["sendMessage","editMessage","saveDraft","clearDraft","showError","setStickerSearchQuery","setGifSearchQuery","forwardMessages","openPollModal","closePollModal","closePaymentModal","clearReceipt","loadScheduledHistory","openChat"]))(({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:a,onDropHide:r,editingMessage:o,chatId:l,threadId:d,messageListType:b,draft:u,chat:O,connectionState:j,isChatWithBot:f,isChatWithSelf:p,isRightColumnShown:I,isSelectModeActive:v,isForwarding:y,canSuggestMembers:C,isPollModalOpen:w,isPaymentModalOpen:E,isReceiptModalOpen:M,botKeyboardMessageId:S,withScheduledButton:k,stickersForEmoji:N,groupChatMembers:P,currentUserId:T,usersById:x,lastSyncTime:R,contentToBeScheduled:L,shouldSuggestStickers:F,sendMessage:D,editMessage:B,saveDraft:U,clearDraft:H,showError:q,setStickerSearchQuery:G,setGifSearchQuery:_,forwardMessages:z,openPollModal:W,closePollModal:V,loadScheduledHistory:$,closePaymentModal:Q,openChat:Y,clearReceipt:J})=>{const X=Object(c.q)(null),[ee,ae]=Object(c.r)(""),se=Object(c.q)(),ce=Object(He.a)(e),[re,oe,ie]=Object(nt.a)(),[le,be]=Object(c.r)(),ue=Object(c.q)(ee);Object(c.n)(()=>{ue.current=ee},[ee]),Object(c.n)(()=>{se.current=void 0},[l]),Object(c.n)(()=>{l&&R&&d===i.MAIN_THREAD_ID&&$()},[l,$,R,d]),Object(c.o)(()=>{X.current&&(X.current.innerHTML='')},[]),Object(c.n)(()=>{L&&(be(L),oe())},[L,oe]);const[me,he]=Object(c.r)([]),[Oe,je,ge]=Object(nt.a)(),[fe,pe,Ie]=Object(nt.a)(),[ve,ye,Ce]=Object(nt.a)(),[we,Ee,Me]=Object(nt.a)(),[Se,ke]=Object(nt.a)(),[Ne,Pe,Te]=Object(nt.a)(),{startRecordingVoice:Ae,stopRecordingVoice:xe,pauseRecordingVoice:Re,activeVoiceRecording:Le,currentRecordTime:De,recordButtonRef:Be,startRecordTimeRef:Ue}=(()=>{const e=Object(c.q)(null),[t,a]=Object(c.r)(),s=Object(c.q)(),[n,r]=Object(c.r)();Object(c.n)(()=>{h.d&&Xa()},[]);const o=Object(c.m)(async()=>{try{const{stop:t,pause:n}=await es(t=>{e.current&&(s.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))});s.current=Date.now(),r(Date.now()),a({stop:t,pause:n})}catch(e){console.error(e)}},[]),i=Object(c.m)(()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}},[t]),l=Object(c.m)(()=>{if(t){a(void 0),s.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}},[t]);return Object(c.n)(()=>t?Object(Z.a)(l):void 0,[t,l]),{startRecordingVoice:o,pauseRecordingVoice:i,stopRecordingVoice:l,activeVoiceRecording:t,currentRecordTime:n,recordButtonRef:e,startRecordTimeRef:s}})(),qe=o?Ns.Edit:!h.l||Le||ee&&!me.length||y?Ns.Send:Ns.Record,Ge=!t,{isMentionMenuOpen:_e,mentionFilter:ze,closeMentionMenu:We,insertMention:Ve,mentionFilteredMembers:$e}=Object(rs.a)(C&&!me.length,ee,ae,void 0,P,T,x),{isContextMenuOpen:Qe,handleContextMenu:Ke,handleContextMenuClose:Ye,handleContextMenuHide:Je}=Object(vt.a)(Be,!(qe===Ns.Send&&Ge)),Xe=Object(c.p)(()=>Object(m.c)(O,f),[O,f]),et=O&&Object(m.fb)(O),tt=Object(m.k)(O),{isEmojiTooltipOpen:at,closeEmojiTooltip:st}=function(e,t,a){const{loadStickersForEmoji:n,clearStickersForEmoji:r}=Object(s.d)(),o=h.c&&1===Object(cs.a)(t)||!h.c&&Boolean(t.match(/^]*?>$/g)),i=Boolean(a)&&o;return Object(c.n)(()=>{e&&o?n({emoji:t}):!i&&o||r()},[t,o,r,n,e]),{isEmojiTooltipOpen:i,closeEmojiTooltip:r}}(Boolean(F&&Xe.canSendStickers&&!me.length),ee,N),ct=Object(c.m)(e=>{const t=window.getSelection(),a=document.getElementById(n.u),s=Object(Ze.a)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(t.rangeCount){const n=t.getRangeAt(0);if(Object(Va.a)(n))return void(h.c?document.execCommand("insertText",!1,e):(!function(e){const t=window.getSelection();if(t&&t.getRangeAt&&t.rangeCount){const a=t.getRangeAt(0);a.deleteContents();const s=a.createContextualFragment(e),n=s.lastChild;a.insertNode(s),n&&(a.setStartAfter(n),a.setEndAfter(n),t.removeAllRanges(),t.addRange(a))}}(s),a.dispatchEvent(new Event("input",{bubbles:!0}))));ae(`${ue.current}${s}`),h.f||requestAnimationFrame(()=>{Object(Ga.a)(a)})}else ae(`${ue.current}${s}`)},[]),rt=Object(c.m)(()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if(Object(Va.a)(t))return void document.execCommand("delete",!1)}ae(function(e){const t=document.createElement("div");t.contentEditable="true",t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t);let a=t.lastChild;if(a.lastChild)for(;a.lastChild;)a=a.lastChild;const s=a.textContent.length,n=document.createRange(),c=window.getSelection();n.setStart(a,s),n.setEnd(a,s),c.removeAllRanges(),c.addRange(n),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(ue.current))},[]),ot=Object(c.m)(()=>{ae(""),he([]),st(),ie(),be(void 0),We(),h.f?setTimeout(()=>Ce(),350):Ce()},[st,ie,We,Ce]),it=Object(He.a)(l);Object(c.n)(()=>{it&&l!==it&&(xe(),ot())},[l,it,ot,xe]);const lt=((e,t,a,s,r,o)=>{Object(c.n)(()=>{a?(t(as(a.content.text)),requestAnimationFrame(()=>{const e=document.getElementById(n.u);Object(Ga.a)(e,!0)})):t("")},[a,t]);return Object(c.m)(()=>{const{text:t,entities:n}=Object(_a.a)(e.current);a&&(t||Object(m.bb)(a)?(o({messageId:a.id,text:t,entities:n}),s()):r())},[o,a,e,r,s])})(ue,ae,o,ot,Ee,B);((e,t,a,s,r,o,i,l,d)=>{const b=Object(c.m)((e,t)=>{r.current.length&&!i?l({chatId:e,threadId:t,draft:Object(_a.a)(r.current)}):d({chatId:e,threadId:t})},[d,i,r,l]),u=Object(c.p)(()=>Object(g.a)(e=>e(),n.t,!1),[t]),m=Object(He.a)(t),h=Object(He.a)(a);Object(c.n)(()=>(ss=t,ns=a,()=>{ss=void 0,ns=void 0,b(t,a)}),[t,a,b]),Object(c.n)(()=>{t===m&&a===h||e&&(o(as(e)),requestAnimationFrame(()=>{const e=document.getElementById(n.u);Object(Ga.a)(e,!0)}))},[t,a,e,o,b,m,h]);const O=Object(He.a)(s);Object(c.n)(()=>{t&&a&&m===t&&h===a&&O!==s&&(s.length?u(()=>{ss===t&&ns===a&&b(t,a)}):b(t,a))},[t,s,m,O,h,u,a,b]),Object(c.n)(()=>{function e(){t&&a&&b(t,a)}return window.addEventListener("blur",e),()=>{window.removeEventListener("blur",e)}},[t,a,b])})(u,l,d,ee,ue,ae,o,U,H),((e,t,a)=>{Object(c.n)(()=>{async function s(s){if(!s.clipboardData)return;const c=document.activeElement;if(c&&"INPUT"===c.tagName&&![n.u,n.v].includes(c.id))return;const{items:r}=s.clipboardData,o=Array.from(r).find(e=>ts.includes(e.type)),i=o&&o.getAsFile(),l=s.clipboardData.getData("text").substring(0,4096);if(i||l){if(s.preventDefault(),i&&!a){const e=await Wa(i.name,i,!0);t(t=>[...t,e])}l&&e(l)}}return document.addEventListener("paste",s,!1),()=>{document.removeEventListener("paste",s,!1)}},[e,a,t])})(ct,he,o);const dt=Object(c.m)(async(e,t)=>{he(await Promise.all(e.map(e=>Wa(e.name,e,t))))},[]),bt=Object(c.m)(()=>{he([])},[]),ut=Object(c.m)(async(e=!1,t)=>{if("connectionStateReady"!==j)return;let a=me;if(Le){const e=await xe();if(e){const{blob:t,duration:s,waveform:n}=e;a=[await Wa("wonderful-voice-message.ogg",t,!1,{voice:{duration:s,waveform:n}})]}}const{text:s,entities:c}=Object(_a.a)(ue.current);if(a.length||s||y)if(a.length&&s&&s.length>1024){const e=s.length-1024;q({error:{message:"CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""}}})}else{if(a.length||s){if(tt&&!et){const e=Math.floor(Date.now()/1e3),t=se.current&&Math.floor(e-se.current),a=tt.nextSendDate&&tt.nextSendDate>e;if(t&&t{e={...e,isPreloadedGlobally:!0},t?(be({sticker:e}),oe()):(D({sticker:e}),requestAnimationFrame(ot))},[t,oe,D,ot]),ht=Object(c.m)(e=>{t?(be({gif:e}),oe()):(D({gif:e}),requestAnimationFrame(ot))},[t,oe,D,ot]),Ot=Object(c.m)(e=>{t?(be({poll:e}),V(),oe()):(D({poll:e}),V())},[V,oe,D,t]),jt=Object(c.m)(()=>{t?(be({isSilent:!0}),oe()):ut(!0)},[ut,oe,t]),gt=Object(c.m)(e=>{const{isSilent:t,...a}=le||{},s=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3);le&&0!==Object.keys(a).length?(D({...le,scheduledAt:s}),requestAnimationFrame(ot)):ut(!!t,s),ie()},[ie,ut,ot,le,D]),ft=Object(c.m)(()=>{gt(new Date(1e3*n.kb))},[gt]),pt=Object(c.m)(()=>{ie(),be(void 0)},[ie]),It=Object(c.m)(e=>{"stickers"===e?(G({query:""}),_({query:void 0})):(_({query:""}),G({query:void 0}))},[G,_]),yt=Object(c.m)(()=>{const e=document.getElementById(n.u);h.f&&e===document.activeElement?(e.blur(),setTimeout(()=>{ye()},100)):ye()},[ye]),Ct=Object(c.m)(()=>{Y({id:l,threadId:d,type:"scheduled"})},[Y,l,d]);Object(c.n)(()=>{I&&h.f&&Ce()},[I,Ce]),Object(c.n)(()=>{v?Pe():setTimeout(()=>{Te()},200)},[v,Te,Pe]);const wt=Object(c.m)(()=>{switch(qe){case Ns.Send:t?(Le&&Re(),oe()):(ut(),requestAnimationFrame(ot));break;case Ns.Record:Ae();break;case Ns.Edit:lt()}},[qe,ot,t,Ae,lt,Le,oe,Re,ut]),Et=Object(te.a)(),Mt=qe===Ns.Record&&!Xe.canAttachMedia,St=Object(He.a)(o,!0),kt=o||St,Nt=new Date;Nt.setSeconds(0),Nt.setMilliseconds(0);const Pt=new Date;Pt.setFullYear(Pt.getFullYear()+1);let Tt="Send message";switch(qe){case Ns.Edit:Tt="Save edited message";break;case Ns.Record:Tt=Mt?"Posting media content is not allowed in this group.":"Record a voice message"}const At=Object(K.a)("Composer",!v&&"shown",Ne&&"hover-disabled"),xt=Object(K.a)("mobile-symbol-menu-button",Se?ve&&"menu-opened":ve&&"is-loading");return c.a.createElement("div",{className:At},Xe.canAttachMedia&&c.a.createElement(Ms.a,{containerId:"#middle-column-portals"},c.a.createElement(Cs,{isOpen:e!==Fe.a.None,withQuick:[e,ce].includes(Fe.a.QuickFile),onHide:r,onFileSelect:dt})),c.a.createElement(vs,{attachments:me,caption:me.length?ee:"",canSuggestMembers:C,groupChatMembers:P,currentUserId:T,usersById:x,onCaptionUpdate:ae,onSend:t?oe:ut,onClear:bt}),c.a.createElement(ys,{isOpen:Boolean(w),onClear:V,onSend:Ot}),c.a.createElement(ks,{isOpen:Boolean(E),onClose:Q}),c.a.createElement(Ps,{isOpen:Boolean(M),onClose:J}),kt&&c.a.createElement(os,{isOpen:we,isSchedule:"scheduled"===b,onClose:Me,message:kt}),c.a.createElement(hs,{isOpen:_e,filter:ze,onClose:We,onInsertUserName:Ve,filteredChatMembers:$e,usersById:x}),c.a.createElement("div",{id:"message-compose"},c.a.createElement("div",{className:"svg-appendix",ref:X}),c.a.createElement(Is,null),c.a.createElement(Es,{chatId:l,threadId:d,messageText:me.length?"":ee,disabled:!Xe.canAttachEmbedLinks}),c.a.createElement("div",{className:"message-input-wrapper"},h.f?c.a.createElement(ne.a,{className:xt,round:!0,color:"translucent",onClick:ve?Ce:yt,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"}),c.a.createElement("i",{className:"icon-keyboard"}),c.a.createElement(de.a,{color:"gray"})):c.a.createElement(bs,{className:""+(ve?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:ye,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"})),c.a.createElement(fs.a,{id:"message-input-text",html:me.length?"":ee,placeholder:Le&&window.innerWidth<=600?"":Et("Message"),shouldSetFocus:ve,shouldSupressFocus:h.f&&ve,onUpdate:ae,onSend:qe===Ns.Edit?lt:t?oe:ut,onSupressedFocus:Ce}),k&&c.a.createElement(ne.a,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:Ct,ariaLabel:"Open scheduled messages"},c.a.createElement("i",{className:"icon-schedule"})),S&&!Le&&!o&&c.a.createElement(bs,{className:""+(Oe?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:je,ariaLabel:"Open bot command keyboard"},c.a.createElement("i",{className:"icon-bot-command"})),!Le&&!o&&c.a.createElement(bs,{className:""+(fe?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:pe,ariaLabel:"Add an attachment"},c.a.createElement("i",{className:"icon-attach"})),Le&&De&&c.a.createElement("span",{className:"recording-state"},Object(A.i)(De-Ue.current)),c.a.createElement(js,{isOpen:at,onStickerSelect:mt}),c.a.createElement(us,{isOpen:fe,allowedAttachmentOptions:Xe,onFileSelect:dt,onPollCreate:W,onClose:Ie}),S&&c.a.createElement(gs,{messageId:S,isOpen:Oe,onClose:ge}),c.a.createElement(ms,{isOpen:ve,allowedAttachmentOptions:Xe,onLoad:ke,onClose:Ce,onEmojiSelect:ct,onStickerSelect:mt,onGifSelect:ht,onRemoveSymbol:rt,onSearchOpen:It}))),Le&&c.a.createElement(ne.a,{round:!0,color:"danger",className:"cancel",onClick:xe,ariaLabel:"Cancel voice recording"},c.a.createElement("i",{className:"icon-delete"})),c.a.createElement(ne.a,{ref:Be,round:!0,color:"secondary",className:`${qe} ${Le?"recording":""}`,disabled:Mt,ariaLabel:Tt,onClick:wt,onContextMenu:qe===Ns.Send&&Ge?Ke:void 0},c.a.createElement("i",{className:"icon-send"}),c.a.createElement("i",{className:"icon-microphone-alt"}),c.a.createElement("i",{className:"icon-check"})),Ge&&c.a.createElement(Os,{isOpen:Qe,onSilentSend:p?void 0:jt,onScheduleSend:t?void 0:oe,onClose:Ye,onCloseAnimationEnd:Je}),c.a.createElement(Ss,{isOpen:re,withTimePicker:!0,selectedAt:Nt.getTime(),maxAt:Object(A.k)(Pt),isFutureMode:!0,secondButtonLabel:a?"Send When Online":void 0,onClose:pt,onSubmit:gt,onSecondButtonClick:a?ft:void 0}))}));var As=e=>{const{isActive:t}=e,a=Object(Ie.a)(pe.a.Extra,"MobileSearch",!t,!0);return a?c.a.createElement(a,e):void 0};var xs=e=>{const{isActive:t}=e,a=Object(Ie.a)(pe.a.Extra,"MessageSelectToolbar",!t);return a?c.a.createElement(a,e):void 0};var Rs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"UnpinAllMessagesModal",!t);return a?c.a.createElement(a,e):void 0};a(232);const Ls=h.f?450+n.c:void 0;function Fs(e){return"file"===e.kind&&e.type&&n.k.includes(e.type)}var Ds=Object(c.h)(Object(s.h)(e=>{const{isBackgroundBlurred:t,customBackground:a,patternColor:s}=e.settings.byKey,n=Boolean((a||"").match(/^#[a-f\d]{6,8}$/i)),c=Object(o.y)(e),{chats:{listIds:r}}=e;if(!c||!r.active)return{customBackground:a,isBackgroundBlurred:t,isCustomBackgroundColor:n};const{chatId:i,threadId:l,type:d}=c,b=Object(o.f)(e,i),u=Object(o.gb)(e,i),{chatId:O,messageId:j}=e.audioPlayer,g=b&&Object(m.e)(b,l),f=Object(o.K)(e,i),p="pinned"===d;return{chatId:i,threadId:l,messageListType:d,isPrivate:Object(m.kb)(i),canPost:!p&&(!b||g)&&(!f||h.f),isPinnedMessageList:p,messageSendingRestrictionReason:b&&Object(m.J)(b),hasPinnedOrAudioMessage:Boolean(u&&u.length)||Boolean(O&&j),customBackground:a,patternColor:s,isCustomBackgroundColor:n,isRightColumnShown:Object(o.V)(e),isBackgroundBlurred:t,isMobileSearchActive:Boolean(h.f&&Object(o.A)(e)),isSelectModeActive:Object(o.R)(e),animationLevel:e.settings.byKey.animationLevel}},(e,t)=>Object(d.l)(t,["openChat","unpinAllMessages","loadUser"]))(({chatId:e,threadId:t,messageListType:a,isPrivate:s,isPinnedMessageList:r,canPost:o,messageSendingRestrictionReason:l,hasPinnedOrAudioMessage:d,customBackground:b,patternColor:u,isCustomBackgroundColor:m,isRightColumnShown:O,isBackgroundBlurred:j,isMobileSearchActive:g,isSelectModeActive:f,animationLevel:p,openChat:I,unpinAllMessages:v,loadUser:y})=>{const{width:C}=Ue(),[w,E]=Object(c.r)(Fe.a.None),[M,S]=Object(c.r)(!1),[k,N]=Object(c.r)(!1),P=qe(e,Ls),T=qe(t,Ls),A=qe(a,Ls),x=qe(o,Ls);Object(c.n)(()=>e?Object(Z.a)(()=>{I({id:void 0})}):void 0,[e,I]),Object(c.n)(()=>{E(Fe.a.None)},[e]),Object(c.n)(()=>{s&&y({userId:e})},[e,s,y]);const R=Object(c.m)(e=>{if(h.k)return;const{items:t}=e.dataTransfer||{},a=t&&Array.from(t).every(Fs);E(a?Fe.a.QuickFile:Fe.a.Document)},[]),L=Object(c.m)(()=>{E(Fe.a.None)},[]),F=Object(c.m)(()=>{N(!0)},[]),D=Object(c.m)(()=>{N(!1)},[]),B=Object(c.m)(()=>{v({chatId:e}),D(),I({id:e})},[v,I,D,e]),U=(e=>{const[t,a]=Object(c.r)(e);return Object(c.n)(()=>{e&&(e.startsWith("#")?a(e):De.c(n.l,n.l,De.a.Blob).then(e=>{a("url("+URL.createObjectURL(e))}))},[e]),t})(b),H=d&&(Cn.Z&&C=n.Y&&CGe(C,x),[x,C]),Y=Object(te.a)();return c.a.createElement("div",{id:"MiddleColumn",className:q,style:`\n --composer-hidden-scale: ${_};\n --toolbar-hidden-scale: ${z};\n --unpin-hidden-scale: ${$};\n --toolbar-unpin-hidden-scale: ${Q};\n --composer-translate-x: ${W}px;\n --toolbar-translate-x: ${V}px;\n --pattern-color: ${u};\n `},c.a.createElement("div",{id:"middle-column-bg",style:U?"--custom-background: "+U:void 0}),c.a.createElement("div",{id:"middle-column-portals"}),P&&T&&c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"messages-layout",onDragEnter:x?R:void 0},c.a.createElement(bt,{chatId:P,threadId:T,messageListType:A}),c.a.createElement(X.a,{name:p===n.e?"slide":"fade",activeKey:"thread"===A&&T===i.MAIN_THREAD_ID?1:2,shouldCleanup:!0},()=>c.a.createElement(c.a.Fragment,null,c.a.createElement(Ha,{key:`${P}-${T}-${A}`,chatId:P,threadId:T,type:A,hasTools:H,onFabToggle:S,bottomOffset:x?"none":r?"big":"small"}),c.a.createElement("div",{className:Object(K.a)("middle-column-footer",!x&&"no-composer")},x&&c.a.createElement(Ts,{chatId:P,threadId:T,messageListType:A,dropAreaState:w,onDropHide:L}),r&&c.a.createElement("div",{className:"unpin-button-container"},c.a.createElement(ne.a,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:F},c.a.createElement("i",{className:"icon-unpin"}),c.a.createElement("span",null,Y("Chat.PanelHidePinnedMessages")))),!r&&!x&&l&&c.a.createElement("div",{className:G},c.a.createElement("div",{className:"messaging-disabled-inner"},c.a.createElement("span",null,l))),c.a.createElement(xs,{messageListType:A,isActive:f,canPost:x})))),c.a.createElement(qa,{isShown:M})),h.f&&c.a.createElement(As,{isActive:Boolean(g)})),e&&c.a.createElement(Rs,{isOpen:k,chatId:e,onClose:D,onUnpin:B}))}));a(233);const Bs=Object(g.a)(e=>e(),200,!1);var Us;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupMembers=16]="ManageGroupMembers",e[e.StickerSearch=17]="StickerSearch",e[e.GifSearch=18]="GifSearch",e[e.PollResults=19]="PollResults"}(Us||(Us={}));var Hs=Object(c.h)(Object(s.h)((e,{chatId:t,isProfile:a,isManagement:s})=>{const{query:n}=Object(o.A)(e)||{},{query:c}=Object(o.z)(e)||{},{query:r}=Object(o.s)(e)||{},i=t?Object(o.f)(e,t):void 0,l=i&&Object(m.ib)(i);return{canManage:Boolean(!s&&a&&i&&!Object(o.O)(e,i.id)&&(Object(m.kb)(i.id)||(Object(m.fb)(i)||i.isCreator)&&!i.isNotJoined)),isChannel:l,messageSearchQuery:n,stickerSearchQuery:c,gifSearchQuery:r}},(e,t)=>Object(d.l)(t,["setLocalTextSearchQuery","setStickerSearchQuery","setGifSearchQuery","searchTextMessagesLocal","toggleManagement","searchMessagesByDate"]))(({isColumnOpen:e,isProfile:t,isSearch:a,isManagement:s,isStickerSearch:n,isGifSearch:r,isPollResults:o,profileState:i,managementScreen:d,canManage:b,isChannel:u,onClose:m,messageSearchQuery:O,stickerSearchQuery:j,gifSearchQuery:g,setLocalTextSearchQuery:f,setStickerSearchQuery:p,setGifSearchQuery:I,searchTextMessagesLocal:v,toggleManagement:y,searchMessagesByDate:C})=>{var w;const E=Object(c.q)(null),[M,S,k]=Object(nt.a)(),N=Object(c.m)(e=>{f({query:e}),e.length&&Bs(v)},[v,f]),P=Object(c.m)(e=>{C({timestamp:e.valueOf()/1e3}),k()},[k,C]),T=Object(c.m)(e=>{p({query:e})},[p]),A=Object(c.m)(e=>{I({query:e})},[I]),[x,R]=Object(c.r)(!e);Object(c.n)(()=>{setTimeout(()=>{R(!e)},300)},[e]);const L=Object(te.a)(),F=t?i===l.k.Profile?Us.Profile:i===l.k.SharedMedia?Us.SharedMedia:i===l.k.MemberList?Us.MemberList:-1:a?Us.Search:o?Us.PollResults:n?Us.StickerSearch:r?Us.GifSearch:s?d===l.g.Initial?Us.ManageInitial:d===l.g.ChatPrivacyType?Us.ManageChatPrivacyType:d===l.g.Discussion?Us.ManageDiscussion:d===l.g.ChannelSubscribers?Us.ManageChannelSubscribers:d===l.g.GroupPermissions?Us.ManageGroupPermissions:d===l.g.ChatAdministrators?Us.ManageChatAdministrators:d===l.g.GroupRemovedUsers?Us.ManageGroupRemovedUsers:d===l.g.GroupUserPermissionsCreate?Us.ManageGroupUserPermissionsCreate:d===l.g.GroupUserPermissions?Us.ManageGroupUserPermissions:d===l.g.GroupRecentActions?Us.ManageGroupRecentActions:d===l.g.ChatAdminRights?Us.ManageGroupAdminRights:d===l.g.GroupMembers?Us.ManageGroupMembers:void 0:void 0,D=null!==(w=We(F,!0))&&void 0!==w?w:-1;function B(){if(-1!==D)switch(D){case Us.PollResults:return c.a.createElement("h3",null,L("PollResults"));case Us.Search:return c.a.createElement(c.a.Fragment,null,c.a.createElement(ce.a,{value:O,onChange:N}),c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",onClick:S,ariaLabel:"Search messages by date"},c.a.createElement("i",{className:"icon-calendar"})));case Us.ManageInitial:return c.a.createElement("h3",null,L("Edit"));case Us.ManageChatPrivacyType:return c.a.createElement("h3",null,L(u?"ChannelTypeHeader":"GroupTypeHeader"));case Us.ManageDiscussion:return c.a.createElement("h3",null,L("Discussion"));case Us.ManageChatAdministrators:return c.a.createElement("h3",null,L("ChannelAdministrators"));case Us.ManageGroupRecentActions:return c.a.createElement("h3",null,L("Group.Info.AdminLog"));case Us.ManageGroupAdminRights:return c.a.createElement("h3",null,L("EditAdminRights"));case Us.ManageGroupPermissions:return c.a.createElement("h3",null,L("ChannelPermissions"));case Us.ManageGroupRemovedUsers:return c.a.createElement("h3",null,L("ChannelBlockedUsers"));case Us.ManageGroupUserPermissionsCreate:return c.a.createElement("h3",null,L("ChannelAddException"));case Us.ManageGroupUserPermissions:return c.a.createElement("h3",null,L("UserRestrictions"));case Us.StickerSearch:return c.a.createElement(ce.a,{value:j,placeholder:"Search Stickers",onChange:T});case Us.GifSearch:return c.a.createElement(ce.a,{value:g,placeholder:L("SearchGifsTitle"),onChange:A});case Us.SharedMedia:return c.a.createElement("h3",null,L("SharedMedia"));case Us.ManageChannelSubscribers:return c.a.createElement("h3",null,L("ChannelSubscribers"));case Us.MemberList:case Us.ManageGroupMembers:return c.a.createElement("h3",null,L("GroupMembers"));default:return c.a.createElement(c.a.Fragment,null,c.a.createElement("h3",null,"Profile"),c.a.createElement("section",{className:"tools"},b&&c.a.createElement(ne.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:L("Edit"),onClick:y},c.a.createElement("i",{className:"icon-edit"}))))}}const U=h.f||F===Us.SharedMedia||F===Us.MemberList||s,H=Object(K.a)("animated-close-icon",x&&"no-transition");return Object(c.n)(()=>{E.current.classList.toggle("state-back",U)},[U]),c.a.createElement("div",{className:"RightHeader"},c.a.createElement(ne.a,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:m,ariaLabel:L(U?"Common.Back":"Common.Close")},c.a.createElement("div",{ref:E,className:H})),c.a.createElement(X.a,{name:x?"none":"slide-fade",activeKey:D},B),!h.f&&c.a.createElement(Ss,{isOpen:M,isPastMode:!0,submitButtonLabel:L("JumpToDate"),onClose:k,onSubmit:P}))})),qs=a(118);function Gs(e,t,a,s,r,o,i,l,d,b,u){const h="members"!==s&&r?r:s,O=Object(c.p)(()=>{if(o&&i)return Object(m.Cb)(o.map(({userId:e})=>e),i)},[o,i]),[j,g,f]=function(e,t,a,s){const[c,r]=Object(qs.a)(a?t:void 0,s,void 0,n.Q),o=!c||!s||c[0]===s[0];return[c,r,!o]}(0,t,u,O),[p,I,v]=_s("media",h,a,u,l,d),[y,C,w]=_s("documents",h,a,u,l,d),[E,M,S]=_s("links",h,a,u,l,d),[k,N,P]=_s("audio",h,a,u,l,d);let T,A,x=!1;switch(h){case"members":T=j,A=g,x=f;break;case"media":T=p,A=I,x=v;break;case"documents":T=y,A=C,x=w;break;case"links":T=E,A=M,x=S;break;case"audio":T=k,A=N,x=P}return[h,T,A,x]}function _s(e,t,a,s,r,o){const i=Object(c.q)();Object(me.a)(()=>{t===e&&r&&o&&(i.current=Object(m.w)(r,o,e).reverse())},[r,o,t,e]);const[l,d]=Object(qs.a)(s?a:void 0,i.current,void 0,"media"===e?n.mb:n.W);return[l,d,!(!l||!i.current||l[0]===i.current[0])]}var zs=a(52);const Ws=Object(g.g)(e=>e(),250,!1);let Vs=!1;var $s=a(102),Qs=a(95);var Ks=a(122),Ys=a(173);a(234);var Js=Object(c.h)(({chat:e,user:t,photo:a,isFirstPhoto:s,isSavedMessages:n,lastSyncTime:r,onClick:o})=>{const l=t&&Object(m.ob)(t);function d(s="big",c){if(a&&!c)return`photo${a.id}?size=c`;let r;return n||l||(t?r=Object(m.f)(t,s):e&&(r=Object(m.f)(e,s))),r}const b=d(),u=Object(Xe.a)(b,!1,i.ApiMediaFormat.BlobUrl,r),h=Object(Xe.a)(!u&&s?d("normal",!0):void 0,!1,i.ApiMediaFormat.BlobUrl,r),O=Object(Ys.a)(!u&&a&&a.thumbnail&&a.thumbnail.dataUri),j=u||h||O,g=Object(He.a)(j);let f="";if(n)f=c.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(l)f=c.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(j)f=c.a.createElement("img",{src:j,className:"avatar-media",alt:"",decoding:"async"});else if(!j&&t){const e=Object(m.Y)(t);f=e?Object(Ve.c)(e,2):void 0}else if(!j&&e){const t=Object(m.l)(e);f=t&&Object(Ve.c)(t,Object(m.kb)(e.id)?2:1)}else f=c.a.createElement("div",{className:"spinner-wrapper"},c.a.createElement(de.a,{color:"white"}));const p=Object(K.a)("ProfilePhoto","color-bg-"+Object(m.W)(t||e),n&&"saved-messages",l&&"deleted-account",!n&&!j&&"no-photo");return c.a.createElement("div",{className:p,onClick:j?o:void 0},g&&j&&g!==j&&c.a.createElement("img",{src:g,className:"prev-avatar-media",alt:"",decoding:"async"}),"string"==typeof f?Object(Ze.a)(f,["hq_emoji"]):f)});a(235);var Zs=Object(c.h)(Object(s.h)((e,{userId:t,forceShowSelf:a})=>{const{lastSyncTime:s}=e,n=Object(o.Db)(e,t),c=Object(o.f)(e,t),r=!a&&n&&n.isSelf,{animationLevel:i}=e.settings.byKey;return{lastSyncTime:s,user:n,chat:c,isSavedMessages:r,animationLevel:i}},(e,t)=>Object(d.l)(t,["loadFullUser","openMediaViewer"]))(({user:e,chat:t,isSavedMessages:a,lastSyncTime:s,animationLevel:n,loadFullUser:r,openMediaViewer:o})=>{const{id:d}=e||{},{id:b}=t||{},u=e?Object(m.Y)(e):t?t.title:"",O=(e?e.photos:t?t.photos:void 0)||[],j=n>=1?"slide":"none",[g,f]=Object(c.r)(0),p=a||O.length<=1||0===g,I=a||O.length<=1||g===O.length-1;Object(c.n)(()=>{g>O.length&&f(Math.max(0,O.length-1))},[g,O.length]);const v=Object(te.a)();Object(c.n)(()=>{s&&d&&r({userId:d})},[d,r,s]),function(e,t,a){Object(c.n)(()=>{t.slice(a,a+4).forEach(e=>{it.c(`photo${e.id}?size=c`)||it.b(`photo${e.id}?size=c`,i.ApiMediaFormat.BlobUrl)})},[a,t])}(0,O,g);const y=Object(c.m)(()=>{o({avatarOwnerId:d||b,profilePhotoIndex:g,origin:l.h.ProfileAvatar})},[o,d,b,g]),C=Object(c.m)(()=>{p||f(g-1)},[g,p]),w=Object(c.m)(()=>{I||f(g+1)},[g,I]);if(Object(c.n)(()=>{const e=document.querySelector(".profile-slide-container > .active, .profile-slide-container > .to");if(e)return Object(ue.b)(e,{excludedClosestSelector:".navigation",onSwipe:h.k?(e,t)=>{t===ue.a.Right?C():t===ue.a.Left&&w()}:void 0})},[w,C]),!e&&!t)return;function E(){const s=!a&&O&&O.length>0?O[g]:void 0;return c.a.createElement(Js,{key:g,user:e,chat:t,photo:s,isSavedMessages:a,isFirstPhoto:p,onClick:y})}const M=e&&e.isVerified||t&&t.isVerified;return c.a.createElement("div",{className:"ProfileInfo"},c.a.createElement("div",{className:"photo-wrapper"},function(){if(!(a||!O||O.length<=1))return c.a.createElement("div",{className:"photo-dashes"},O.map((e,t)=>c.a.createElement("span",{className:"photo-dash "+(t===g?"current":"")})))}(),c.a.createElement(X.a,{activeKey:g,name:j,className:"profile-slide-container"},E),!p&&c.a.createElement("button",{type:"button",className:"navigation prev","aria-label":v("AccDescrPrevious"),onClick:C}),!I&&c.a.createElement("button",{type:"button",className:"navigation next","aria-label":v("Next"),onClick:w})),c.a.createElement("div",{className:"info"},a?c.a.createElement("div",{className:"title"},c.a.createElement("h3",null,v("SavedMessages"))):c.a.createElement("div",{className:"title"},c.a.createElement("h3",null,u&&Object(Ze.a)(u)),M&&c.a.createElement(Ks.a,null)),!a&&(e?c.a.createElement("div",{className:"status "+(Object(m.wb)(e)?"online":"")},c.a.createElement("span",{className:"user-status"},Object(m.Z)(e,v))):c.a.createElement("span",{className:"status"},Object(m.ib)(t)?v("Subscribers",t.membersCount,"i"):v("Members",t.membersCount,"i")))))}));var Xs=Object(c.h)(Object(s.h)((e,{chatOrUserId:t})=>{const{lastSyncTime:a}=e,s=t?Object(o.f)(e,t):void 0;return{lastSyncTime:a,chat:s,user:Object(m.kb)(t)?Object(o.Db)(e,t):void 0,canInviteUsers:s&&(!Object(m.ib)(s)&&!Object(m.xb)(s,"inviteUsers")||Object(m.q)(s,"inviteUsers"))}},(e,t)=>Object(d.l)(t,["loadFullUser","updateChatMutedState","showNotification"]))(({lastSyncTime:e,user:t,chat:a,forceShowSelf:s,canInviteUsers:n,loadFullUser:r,showNotification:o,updateChatMutedState:i})=>{const{id:l,fullInfo:d,username:b,phoneNumber:u,isSelf:h}=t||{},{id:O,isMuted:j,username:g}=a||{},f=Object(te.a)();Object(c.n)(()=>{e&&l&&r({userId:l})},[r,l,e]);const p=Object(c.m)((e,t)=>{Object(w.c)(e),o({message:t+" was copied"})},[o]),I=Object(c.m)(()=>{i({chatId:O,isMuted:!j})},[O,j,i]);if(!a||a.isRestricted||h&&!s)return;const v=d&&d.bio,y=u&&Object(da.c)(u),C=Object(m.g)(a),E=Object(m.h)(a),M=0===E.indexOf("http")?E:"http://"+E,S=b||g,k=v||C;return c.a.createElement("div",{className:"ChatExtra"},y&&!!y.length&&c.a.createElement(Qs.a,{icon:"phone",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(y,f("Phone"))},c.a.createElement("span",{className:"title"},y),c.a.createElement("span",{className:"subtitle"},f("Phone"))),S&&c.a.createElement(Qs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p("@"+S,f("Username"))},c.a.createElement("span",{className:"title"},Object(Ze.a)(S)),c.a.createElement("span",{className:"subtitle"},f("Username"))),k&&!!k.length&&c.a.createElement(Qs.a,{icon:"info",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(k,f(l?"UserBio":"Info"))},c.a.createElement("span",{className:"title"},Object(Ze.a)(k,["br","links","emoji"])),c.a.createElement("span",{className:"subtitle"},f(l?"UserBio":"Info"))),n&&!S&&!!E.length&&c.a.createElement(Qs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(E,f("SetUrlPlaceholder"))},c.a.createElement("div",{className:"title"},c.a.createElement(Ia.a,{url:M,className:"title",text:E})),c.a.createElement("span",{className:"subtitle"},f("SetUrlPlaceholder"))),c.a.createElement(Qs.a,{icon:"unmute",onClick:I},c.a.createElement("span",null,f("Notifications")),c.a.createElement(oe,{id:"group-notifications",label:""+(l?"Toggle User Notifications":"Toggle Chat Notifications"),checked:!j,inactive:!0})))})),en=a(155),tn=a(174),an=a(108);a(239);const sn=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"}];function nn(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > div.active > .${e}-list > .scroll-item`].join(", ")}var cn=Object(c.h)(Object(s.h)((e,{chatId:t,userId:a})=>{const s=Object(o.f)(e,t),n=Object(o.m)(e,a||t),{currentType:c,resultsByType:r}=Object(o.v)(e)||{},{foundIds:i}=r&&c&&r[c]||{},{byId:l}=e.users,d=s&&Object(m.jb)(s),b=s&&Object(m.ib)(s),u=d||b&&Object(m.fb)(s),h=s&&s.fullInfo&&s.fullInfo.members,O=u&&s&&s.fullInfo&&!s.fullInfo.canViewMembers;let j;return a?j=a:Object(m.kb)(t)&&(j=t),{isChannel:b,resolvedUserId:j,chatMessages:n,foundIds:i,mediaSearchType:c,hasMembersTab:u,areMembersHidden:O,...u&&h&&{members:h,usersById:l},isRightColumnShown:Object(o.V)(e),isRestricted:s&&s.isRestricted,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(d.l)(t,["setLocalMediaSearchType","loadMoreMembers","searchMediaMessagesLocal","openMediaViewer","openAudioPlayer","openUserInfo","focusMessage","loadProfilePhotos"]))(({chatId:e,profileState:t,onProfileStateChange:a,isChannel:s,resolvedUserId:r,chatMessages:o,foundIds:d,mediaSearchType:b,hasMembersTab:u,areMembersHidden:m,members:O,usersById:j,isRightColumnShown:g,isRestricted:f,lastSyncTime:p,setLocalMediaSearchType:I,loadMoreMembers:v,searchMediaMessagesLocal:y,openMediaViewer:C,openAudioPlayer:w,openUserInfo:E,focusMessage:M,loadProfilePhotos:S})=>{const k=Object(c.q)(null),N=Object(c.q)(null),[P,T]=Object(c.r)(0),A=Object(c.p)(()=>[...u?[{type:"members",title:s?"ChannelSubscribers":"GroupMembers"}]:[],...sn],[u,s]),x=A[P].type,[R,L,F,D]=Gs(0,v,y,x,b,O,j,o,d,0,p),B=A.findIndex(({type:e})=>e===R),{handleScroll:U}=function(e,t,a,s){Object(zs.a)(([a])=>{if(a&&a!==t){const a=e.current,n=a.querySelector(".TabList");a.scrollTop{Vs=!1},350))}},[t,s]),Object(zs.a)(([t])=>{if(a!==l.k.Profile||a===t)return;const n=e.current;if(!n)return;const c=n.querySelector(".TabList");!c||c.offsetTop>n.scrollTop||(Vs=!0,Object(ft.a)(n,n.firstElementChild,"start",void 0,2*n.offsetHeight),setTimeout(()=>{Vs=!1},350),s(a))},[a]);const n=Object(c.m)(()=>{const a=e.current;if(!a)return;const n=a.querySelector(".TabList");if(!n)return;let c=l.k.Profile;a.scrollTop>=n.offsetTop&&(c="members"===t?l.k.MemberList:l.k.SharedMedia),s(c)},[e,s,t]);return Object(c.n)(()=>{Vs||n()},[n,t]),{handleScroll:Object(c.m)(()=>{Vs||Ws(n)},[n])}}(k,x,t,a),{applyTransitionFix:H,releaseTransitionFix:q}=function(e,t=".Transition.shared-media-transition"){return Object(c.n)(()=>{function a(){const a=e.current,s=a.querySelector(t),n=a.querySelector(".TabList");s&&n&&(s.style.minHeight=a.offsetHeight-n.offsetHeight+"px")}return a(),window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[e,t]),{applyTransitionFix:Object(c.m)(()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=e+"px"}},[e]),releaseTransitionFix:Object(c.m)(()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"},[e])}}(k),[G,_]=(()=>{const[e,t]=Object(c.r)(!1);return[e,Object(c.m)(()=>{t(e=>!e)},[])]})(),z=Object(c.m)(()=>{q(),_()},[q,_]);Object(c.n)(()=>{I({mediaType:x})},[I,x]);const W=r||e;Object(c.n)(()=>{p&&S({profileId:W})},[S,W,p]);const V=Object(c.m)(e=>{C({chatId:W,threadId:i.MAIN_THREAD_ID,messageId:e,origin:l.h.SharedMedia})},[W,C]),$=Object(c.m)(e=>{w({chatId:W,messageId:e})},[W,w]),Q=Object(c.m)(e=>{E({id:e})},[E]),K=Object(c.m)(e=>{M({chatId:W,messageId:e})},[W,M]);let Y;Object(c.n)(()=>{if(N.current&&h.k)return Object(ue.b)(N.current,{onSwipe:(e,t)=>{t===ue.a.Left?T(Math.min(P+1,A.length-1)):t===ue.a.Right&&T(Math.max(0,P-1))}})},[P,A.length]);const J="members"===R||!u&&"media"===R;J?Y=g?0:1e3:L||(Y=n.nb);const Z=Object(ps.a)([e,R],Y);function ee(){if(!L||!Z||!o){const e=J&&L&&!Z;return c.a.createElement("div",{className:"content empty-list"},!e&&c.a.createElement(de.a,null))}if(!L.length){let e;switch(R){case"members":e=m?"You have no access to group members list.":"No members found";break;case"documents":e="No documents found.";break;case"links":e="No links found.";break;case"audio":e="No audio found.";break;default:e="No media found."}return c.a.createElement("div",{className:"content empty-list"},c.a.createElement(an.a,{text:e}))}return c.a.createElement("div",{className:`content ${R}-list`,teactFastList:!0},"media"===R?L.map(e=>o[e]&&c.a.createElement(en.a,{key:e,message:o[e],onClick:V})):"documents"===R?L.map(e=>o[e]&&c.a.createElement(_t.a,{key:e,message:o[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:K})):"links"===R?L.map(e=>o[e]&&c.a.createElement(tn.a,{key:e,message:o[e],onMessageClick:K})):"audio"===R?L.map(e=>o[e]&&c.a.createElement(zt.a,{key:e,renderingFor:"sharedMedia",message:o[e],date:o[e].date,lastSyncTime:p,className:"scroll-item",onPlay:$,onDateClick:K})):"members"===R?L.map((e,t)=>c.a.createElement(Qs.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>Q(e)},c.a.createElement($e.a,{userId:e,forceShowSelf:!0}))):void 0)}return c.a.createElement($s.a,{ref:k,className:"Profile custom-scroll",itemSelector:nn(R),items:Z?L:void 0,cacheBuster:G,sensitiveArea:n.eb,preloadBackwards:Z?"members"===R?n.Q:n.mb:0,noFastList:!0,onLoadMore:F,onScroll:U},!D&&function(e,t){return c.a.createElement("div",{className:"profile-info"},c.a.createElement(Zs,{userId:t||e,forceShowSelf:t!==e}),c.a.createElement(Xs,{chatOrUserId:t||e,forceShowSelf:t!==e}))}(e,r),!f&&c.a.createElement("div",{className:"shared-media"},c.a.createElement(X.a,{ref:N,name:"slide",activeKey:B,renderCount:A.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:H,onStop:z},ee),c.a.createElement(je.a,{activeTab:P,tabs:A,onSwitchTab:T})))}));var rn=e=>{const t=Object(Ie.a)(pe.a.Extra,"RightSearch");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var on=e=>{const t=Object(Ie.a)(pe.a.Extra,"Management");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var ln=()=>{const e=Object(Ie.a)(pe.a.Extra,"StickerSearch");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};var dn=()=>{const e=Object(Ie.a)(pe.a.Extra,"GifSearch");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};var bn=()=>{const e=Object(Ie.a)(pe.a.Extra,"PollResults");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};a(240);const un=Object.keys(l.l).length/2,mn=Object.keys(l.g).length/2;function hn(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}var On=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},s=Object(o.d)(e);return{contentKey:Object(o.kb)(e),chatId:t,threadId:a,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&s)}},(e,t)=>Object(d.l)(t,["openUserInfo","toggleChatInfo","toggleManagement","closeLocalTextSearch","setStickerSearchQuery","setGifSearchQuery","closePollResults"]))(({contentKey:e,chatId:t,threadId:a,currentProfileUserId:s,isChatSelected:r,toggleChatInfo:o,toggleManagement:i,openUserInfo:d,closeLocalTextSearch:b,setStickerSearchQuery:u,setGifSearchQuery:m,closePollResults:h})=>{var O;const{width:j}=Ue(),[g,f]=Object(c.r)(l.k.Profile),[p,I]=Object(c.r)(l.g.Initial),[v,y]=Object(c.r)(),[C,w]=Object(c.r)(),E=g!==l.k.Profile,M=void 0!==e,S=e===l.l.ChatInfo||e===l.l.UserInfo,k=e===l.l.Search,N=e===l.l.Management,P=e===l.l.StickerSearch,T=e===l.l.GifSearch,A=e===l.l.PollResults,x=j<=n.Z,[R,L]=Object(c.r)(!M),F=null!==(O=We(e,!0,!r))&&void 0!==O?O:-1,D=Object(c.m)(()=>{switch(e){case l.l.ChatInfo:if(E){f(l.k.Profile);break}o();break;case l.l.UserInfo:if(E){f(l.k.Profile);break}d({id:void 0});break;case l.l.Management:switch(p){case l.g.Initial:i();break;case l.g.ChatPrivacyType:case l.g.Discussion:case l.g.GroupPermissions:case l.g.GroupType:case l.g.ChatAdministrators:case l.g.ChannelSubscribers:case l.g.GroupMembers:I(l.g.Initial);break;case l.g.GroupUserPermissionsCreate:case l.g.GroupRemovedUsers:case l.g.GroupUserPermissions:I(l.g.GroupPermissions),y(void 0),w(void 0);break;case l.g.ChatAdminRights:case l.g.GroupRecentActions:I(l.g.ChatAdministrators)}break;case l.l.Search:hn(),b();break;case l.l.StickerSearch:case l.l.GifSearch:hn(),u({query:void 0}),m({query:void 0});break;case l.l.PollResults:h()}},[e,E,o,d,h,p,i,b,u,m]),B=Object(c.m)((e,t)=>{y(e),w(t)},[]);function U(){if(-1!==F)switch(F){case l.l.ChatInfo:case l.l.UserInfo:return c.a.createElement(cn,{key:s||t,chatId:t,userId:s,profileState:g,onProfileStateChange:f});case l.l.Search:return c.a.createElement(rn,{chatId:t,threadId:a});case l.l.Management:return c.a.createElement(on,{chatId:t,currentScreen:p,isPromotedByCurrentUser:C,selectedChatMemberId:v,onScreenSelect:I,onChatMemberSelect:B});case l.l.StickerSearch:return c.a.createElement(ln,null);case l.l.GifSearch:return c.a.createElement(dn,null);case l.l.PollResults:return c.a.createElement(bn,null)}}return Object(c.n)(()=>M?Object(Z.a)(D):void 0,[M,D]),Object(c.n)(()=>{setTimeout(()=>{L(!M)},300)},[M]),Object(c.n)(()=>{M&&x&&D()},[x]),Object(ut.a)(([a,s])=>{(a===l.l.ChatInfo&&e===l.l.UserInfo||a===l.l.UserInfo&&e===l.l.ChatInfo||s!==t)&&(f(l.k.Profile),I(l.g.Initial))},[e,t]),c.a.createElement("div",{id:"RightColumn-wrapper",className:r?void 0:"is-hidden"},x&&c.a.createElement("div",{className:"overlay-backdrop",onClick:D}),c.a.createElement("div",{id:"RightColumn"},c.a.createElement(Hs,{chatId:t,isColumnOpen:M,isProfile:S,isSearch:k,isManagement:N,isStickerSearch:P,isGifSearch:T,isPollResults:A,profileState:g,managementScreen:p,onClose:D}),c.a.createElement(X.a,{name:R?"none":"zoom-fade",renderCount:un+mn,activeKey:N?un+p:F},U)))}));var jn=Object(c.h)(({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"MediaViewer",!e);return t?c.a.createElement(t,null):void 0});var gn=({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"Notifications",!e);return t?c.a.createElement(t,null):void 0};var fn=({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"Errors",!e);return t?c.a.createElement(t,null):void 0};var pn=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ForwardPicker",!t);return a?c.a.createElement(a,e):void 0};a(241);let In,vn,yn=!1;function Cn(e){document.querySelectorAll('link[rel="icon"]').forEach(t=>{e?t.href.includes("favicon-unread")||(t.href=t.href.replace("favicon","favicon-unread")):t.href=t.href.replace("favicon-unread","favicon")})}var wn=Object(c.h)(Object(s.h)(e=>{const{chatId:t,messageId:a}=e.audioPlayer,s=t&&a?Object(o.k)(e,t,a):void 0;return{animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:Object(o.V)(e),isMediaViewerOpen:Object(o.S)(e),isForwardModalOpen:Object(o.Q)(e),hasNotifications:Boolean(e.notifications.length),hasErrors:Boolean(e.errors.length),audioMessage:s}},(e,t)=>Object(d.l)(t,["loadAnimatedEmojis"]))(({lastSyncTime:e,loadAnimatedEmojis:t,isLeftColumnShown:a,isRightColumnShown:r,isMediaViewerOpen:i,isForwardModalOpen:l,animationLevel:d,hasNotifications:b,hasErrors:u,audioMessage:m})=>{n.o&&!yn&&(yn=!0,console.log(">>> RENDER MAIN")),Object(c.n)(()=>{e&&t()},[e,t]);const{transitionClassNames:h}=Object(Y.a)(!a,void 0,!0),{transitionClassNames:O}=Object(Y.a)(r,void 0,!0),j=Object(K.a)(h.replace(/([\w-]+)/g,"middle-column-$1"),O.replace(/([\w-]+)/g,"right-column-$1"));function g(e){e.preventDefault(),e.stopPropagation()}return Object(c.n)(()=>{document.body.classList.toggle("is-middle-column-open",j.includes("middle-column-open")),document.body.classList.toggle("is-right-column-shown",j.includes("right-column-open"))},[j]),Object(c.n)(()=>{d>0&&(document.body.classList.add("animating-right-column"),Object(Q.b)(350+n.c),In&&(clearTimeout(In),In=void 0),In=window.setTimeout(()=>{document.body.classList.remove("animating-right-column"),In=void 0},350+n.c))},[d,r]),Object(J.a)(()=>{const e=Object(o.q)(Object(s.e)());let t=0;clearInterval(vn),vn=window.setInterval(()=>{if(document.title.includes(n.D))Cn(!1);else{if(t%2==0){const t=Object(o.q)(Object(s.e)())-e;t>0&&(document.title=`${t} notification${t>1?"s":""}`,Cn(!0))}else document.title=n.db,Cn(!1);t++}},1e3)},()=>{clearInterval(vn),vn=void 0,document.title.includes(n.D)||(document.title=n.db),Cn(!1)}),c.a.createElement("div",{id:"Main",className:j,onDrop:g,onDragOver:g},c.a.createElement(Le,null),c.a.createElement(Ds,null),c.a.createElement(On,null),c.a.createElement(jn,{isOpen:i}),c.a.createElement(pn,{isOpen:l}),c.a.createElement(gn,{isOpen:b}),c.a.createElement(fn,{isOpen:u}),m&&c.a.createElement(dt,{key:m.id,message:m,noUi:!0}))}));n.o&&console.log(">>> FINISH LOAD MAIN BUNDLE"),Object(s.e)().connectionState||Object(s.d)().initApi()}}]); -//# sourceMappingURL=3.4cc830a94ce5c77c6a75.js.map \ No newline at end of file +(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{186:function(e,t,a){},187:function(e,t,a){},188:function(e,t,a){},200:function(e,t,a){},201:function(e,t,a){},202:function(e,t,a){},205:function(e,t,a){},206:function(e,t,a){},207:function(e,t,a){},211:function(e,t,a){},212:function(e,t,a){},214:function(e,t,a){},217:function(e,t,a){},218:function(e,t,a){},219:function(e,t,a){},220:function(e,t,a){},221:function(e,t,a){},222:function(e,t,a){},223:function(e,t,a){},224:function(e,t,a){},225:function(e,t,a){},226:function(e,t,a){},227:function(e,t,a){},229:function(e,t,a){},230:function(e,t,a){},231:function(e,t,a){},232:function(e,t,a){},233:function(e,t,a){},234:function(e,t,a){},235:function(e,t,a){},239:function(e,t,a){},240:function(e,t,a){},241:function(e,t,a){},91:function(e,t,a){"use strict";a.r(t),a.d(t,"Main",(function(){return En}));var s=a(2),n=a(1),c=a(0),r=(a(74),a(39)),o=a(6);window.addEventListener("popstate",e=>{if(!e.state)return;const{chatId:t,threadId:a,messageListType:n}=e.state;Object(s.d)().openChat({id:t,threadId:a,type:n,noPushState:!0})}),Object(s.b)("openChat",(e,t,a)=>{const{id:n,threadId:c=-1,type:i="thread",noPushState:l}=a,d=Object(o.y)(e);return d&&d.chatId===n&&d.threadId===c&&d.type===i||(e=Object(r.m)(e),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...n!==e.forwardMessages.toChatId&&{forwardMessages:{}}},Object(s.g)(e),l||window.history.pushState({chatId:n,threadId:c,messageListType:i},"")),Object(r.L)(e,n,c,i)}),Object(s.b)("openChatWithInfo",(e,t,a)=>{Object(s.g)({...e,isChatInfoShown:!0}),t.openChat(a)}),Object(s.b)("resetChatCreation",e=>({...e,chatCreation:void 0}));var i=a(4),l=a(19),d=a(3);let b;Object(s.b)("setScrollOffset",(e,t,a)=>{const{chatId:s,threadId:n,scrollOffset:c}=a;return Object(r.v)(e,s,n,"scrollOffset",c)}),Object(s.b)("setReplyingToId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i}=n;return Object(r.v)(e,c,i,"replyingToId",s)}),Object(s.b)("setEditingId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i,type:l}=n,d="scheduled"===l?"editingScheduledId":"editingId";return Object(r.v)(e,c,i,d,s)}),Object(s.b)("editLastMessage",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(!t||!a)return;const s=Object(o.m)(e,t),n=Object(o.Eb)(e,t,a);if(!s||!n)return;const c=Object(d.g)(n,t=>Boolean(s[t]&&Object(o.b)(e,s[t],a).canEdit));return c?Object(r.v)(e,t,a,"editingId",c):void 0}),Object(s.b)("openMediaViewer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i}=a;return{...e,mediaViewer:{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i},forwardMessages:{}}}),Object(s.b)("closeMediaViewer",e=>({...e,mediaViewer:{}})),Object(s.b)("openAudioPlayer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c}=a;return{...e,audioPlayer:{chatId:s,threadId:n,messageId:c}}}),Object(s.b)("closeAudioPlayer",e=>({...e,audioPlayer:{}})),Object(s.b)("openPollResults",(e,t,a)=>{const{chatId:n,messageId:c}=a;Object(o.V)(e)?n===e.pollResults.chatId&&c===e.pollResults.messageId||Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}}):window.setTimeout(()=>{const e=Object(s.e)();Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}})},450)}),Object(s.b)("closePollResults",e=>{Object(s.g)({...e,pollResults:{}})}),Object(s.b)("focusLastMessage",(e,t)=>{const a=Object(o.y)(e);if(!a)return;const{chatId:s,threadId:n}=a;let c;if(n===i.MAIN_THREAD_ID){const t=Object(o.f)(e,s);c=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.zb)(e,s,n);c=t?t.lastMessageId:void 0}c&&t.focusMessage({chatId:s,threadId:n,messageId:c,noHighlight:!0})}),Object(s.b)("focusMessage",(e,t,a)=>{const{chatId:n,threadId:c=i.MAIN_THREAD_ID,messageListType:d="thread",noHighlight:u,groupedId:m,groupedChatId:h}=a;let{messageId:O}=a;if(void 0!==m){const t=Object(o.I)(e,h,m);t&&t.length&&([O]=t)}const j=Object(o.y)(e),g=!j||n!==j.chatId||c!==j.threadId||d!==j.type;b&&(clearTimeout(b),b=void 0),b=window.setTimeout(()=>{let e=Object(s.e)();e=Object(r.N)(e),e=Object(r.M)(e),Object(s.g)(e)},2e3),e=Object(r.N)(e,n,O,u),e=Object(r.M)(e,void 0),g&&(e=Object(r.M)(e,l.b.Static));const f=Object(o.Eb)(e,n,c);if(f&&f.includes(O))return Object(s.g)(e),void t.openChat({id:n,threadId:c});if(g&&(e=Object(r.v)(e,n,c,"viewportIds",void 0)),e=Object(r.v)(e,n,c,"outlyingIds",void 0),f&&!g){const t=O>f[0]?l.b.Down:l.b.Up;e=Object(r.M)(e,t)}Object(s.g)(e),t.openChat({id:n,threadId:c}),t.loadViewportMessages()}),Object(s.b)("openForwardMenu",(e,t,a)=>{const{fromChatId:s,messageIds:n,groupedId:c}=a;let r;return c&&(r=Object(o.Z)(e,s,c)),{...e,forwardMessages:{fromChatId:s,messageIds:r||n,isModalShown:!0}}}),Object(s.b)("exitForwardMode",e=>{Object(s.g)({...e,forwardMessages:{}})}),Object(s.b)("setForwardChatId",(e,t,a)=>{const{id:n}=a;Object(s.g)({...e,forwardMessages:{...e.forwardMessages,toChatId:n,isModalShown:!1}}),t.openChat({id:n}),t.closeMediaViewer()}),Object(s.b)("openForwardMenuForSelectedMessages",(e,t)=>{if(!e.selectedMessages)return;const{chatId:a,messageIds:s}=e.selectedMessages;t.openForwardMenu({fromChatId:a,messageIds:s})}),Object(s.b)("enterMessageSelectMode",(e,t,a)=>{const{messageId:s}=a||{},n=Object(o.r)(e);return n?Object(r.l)(e,n.id,s):e}),Object(s.b)("toggleMessageSelection",(e,t,a)=>{const{messageId:s,groupedId:n,childMessageIds:c,withShift:i}=a,l=Object(o.y)(e);if(!l)return;const{chatId:d,threadId:b,type:u}=l;return Object(r.E)(e,d,b,u,s,n,c,i)}),Object(s.b)("exitMessageSelectMode",r.m),Object(s.b)("openPollModal",e=>({...e,isPollModalOpen:!0})),Object(s.b)("closePollModal",e=>({...e,isPollModalOpen:!1}));Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{query:s}=a,{chatId:n}=e.globalSearch;return Object(r.P)(e,{globalResults:{},localResults:{},resultsByType:void 0,...s?{fetchingStatus:{chats:!n,messages:!0}}:{fetchingStatus:void 0},query:s})}),Object(s.b)("addRecentlyFoundChatId",(e,t,a)=>{const{id:s}=a,{recentlyFoundChatIds:n}=e.globalSearch;if(!n)return Object(r.P)(e,{recentlyFoundChatIds:[s]});const c=n.filter(e=>e!==s);return c.unshift(s),c.length>10&&c.pop(),Object(r.P)(e,{recentlyFoundChatIds:c})}),Object(s.b)("clearRecentlyFoundChats",e=>Object(r.P)(e,{recentlyFoundChatIds:void 0})),Object(s.b)("setGlobalSearchContent",(e,t,a)=>{const{content:s}=a;return Object(r.Q)(e,s)}),Object(s.b)("setGlobalSearchChatId",(e,t,a)=>{const{id:s}=a;return Object(r.P)(e,{chatId:s,query:void 0,resultsByType:void 0})});var u=a(45),m=a(5);Object(s.b)("openLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return Object(r.W)(e,t,a,!0)}),Object(s.b)("closeLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return e=Object(r.W)(e,t,a,!1),e=Object(r.s)(e,t,a,void 0)}),Object(s.b)("setLocalTextSearchQuery",(e,t,a)=>{const{chatId:s,threadId:n}=Object(o.y)(e)||{};if(!s||!n)return;const{query:c}=a,i=Object(m.a)(s,n),{query:l}=e.localTextSearch.byChatThreadKey[i]||{};return c!==l&&(e=Object(r.s)(e,s,n,u.a)),e=Object(r.W)(e,s,n,!0,c)}),Object(s.b)("setLocalMediaSearchType",(e,t,a)=>{const{chatId:s}=Object(o.y)(e)||{};if(!s)return;const{mediaType:n}=a;return Object(r.V)(e,s,n)}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,stickers:{...e.stickers,search:{query:s,resultIds:void 0}}}}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,gifs:{...e.gifs,search:{query:s,offsetId:void 0,results:void 0}}}}),Object(s.b)("openUserInfo",(e,t,a)=>{const{id:s}=a;t.openChat({id:s})});Object(s.b)("openChat",e=>Object(r.db)(e,void 0)),Object(s.b)("setSettingOption",(e,t,a)=>Object(r.u)(e,a));var h=a(7),O=a(159);Object(s.b)("toggleChatInfo",e=>({...e,isChatInfoShown:!e.isChatInfoShown})),Object(s.b)("toggleManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}}),Object(s.b)("closeManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}}),Object(s.b)("openChat",(e,t,a)=>{if(!h.f)return;const{id:s}=a;return{...e,isLeftColumnShown:void 0===s}}),Object(s.b)("toggleLeftColumn",e=>({...e,isLeftColumnShown:!e.isLeftColumnShown})),Object(s.b)("addRecentEmoji",(e,t,a)=>{const{emoji:s}=a,{recentEmojis:n}=e;if(!n)return{...e,recentEmojis:[s]};const c=n.filter(e=>e!==s);return c.unshift(s),c.length>18&&c.pop(),{...e,recentEmojis:c}}),Object(s.b)("addRecentSticker",(e,t,a)=>{const{sticker:s}=a,{recent:n}=e.stickers;if(!n)return{...e,stickers:{...e.stickers,recent:{hash:0,stickers:[s]}}};const c=n.stickers.filter(e=>e.id!==s.id);return c.unshift(s),{...e,stickers:{...e.stickers,recent:{...n,stickers:c}}}}),Object(s.b)("showNotification",(e,t,a)=>{const s=a,n=[...e.notifications],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,notifications:n}}),Object(s.b)("dismissNotification",e=>{const t=[...e.notifications];return t.pop(),{...e,notifications:t}}),Object(s.b)("showError",(e,t,a)=>{const{error:s}=a;if(!Object(O.a)(s))return e;const n=[...e.errors],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,errors:n}}),Object(s.b)("dismissError",e=>{const t=[...e.errors];return t.pop(),{...e,errors:t}}),Object(s.b)("openPaymentModal",(e,t,a)=>{const{messageId:s}=a;return{...e,payment:{...e.payment,messageId:s,isPaymentModalOpen:!0}}}),Object(s.b)("closePaymentModal",e=>{const t=Object(r.g)(e);return Object(r.h)(t)});a(75);var j=a(10),g=a(9);const f=Object(g.g)(e=>e(),1e3,!0),p=Object(g.g)(e=>e(),3e3,!0),I=Object(g.a)(e=>e(),500,!1,!0);async function v(e,t,a){const c=await Object(j.a)("fetchChats",{limit:n.i,offsetDate:a,archived:"archived"===e,withPinned:void 0===Object(s.e)().chats.orderedPinnedIds[e]});if(!c)return;const{chatIds:o}=c;o.length>0&&o[0]===t&&o.shift();let l=Object(s.e)();l=Object(r.e)(l,Object(d.c)(c.users,"id")),l=Object(r.K)(l,Object(d.c)(c.chats,"id")),l=Object(r.G)(l,e,o),l=Object(r.H)(l,e,c),Object.keys(c.draftsById).map(Number).forEach(e=>{l=Object(r.v)(l,e,i.MAIN_THREAD_ID,"draft",c.draftsById[e])}),Object.keys(c.replyingToById).map(Number).forEach(e=>{l=Object(r.v)(l,e,i.MAIN_THREAD_ID,"replyingToId",c.replyingToById[e])}),0!==o.length||l.chats.isFullyLoaded[e]||(l={...l,chats:{...l.chats,isFullyLoaded:{...l.chats.isFullyLoaded,[e]:!0}}}),Object(s.g)(l)}async function y(e){const t=await Object(j.a)("fetchFullChat",e);if(!t)return;const{users:a,fullInfo:n}=t;let c=Object(s.e)();a&&(c=Object(r.e)(c,Object(d.c)(a,"id"))),c=Object(r.F)(c,e.id,{fullInfo:n}),Object(s.g)(c)}async function C(e,t,a){const n=Object(s.e)(),c=Object(o.h)(n,t);if(c&&!c.isMin)return void(a?e.focusMessage({chatId:c.id,messageId:a}):e.openChat({id:c.id}));const i=Object(o.r)(n);e.openChat({id:-1});const l=await Object(j.a)("getChatByUsername",t);if(!l)return i&&e.openChat({id:i.id}),void e.showNotification({message:"User does not exist"});Object(s.g)(Object(r.F)(Object(s.e)(),l.id,l)),a?e.focusMessage({chatId:l.id,messageId:a}):e.openChat({id:l.id})}Object(s.b)("preloadTopChatMessages",(e,t)=>{(async()=>{const a=[];for(let c=0;ce!==l&&!a.includes(e));if(!u)return;a.push(u.id),t.loadViewportMessages({chatId:u.id,threadId:i.MAIN_THREAD_ID}),h.k&&t.loadPinnedMessages({chatId:u.id})}})()}),Object(s.b)("openChat",(e,t,a)=>{const{id:s,threadId:n}=a,{currentUserId:c}=e,r=Object(o.f)(e,s);if(r&&r.hasUnreadMark&&t.toggleChatUnread({id:s}),r)Object(m.lb)(r)&&!r.isMin&&t.requestChatUpdate({chatId:s});else if(s===c)Object(j.a)("fetchChat",{type:"self"});else{const t=Object(o.Db)(e,s);t&&Object(j.a)("fetchChat",{type:"user",user:t})}if(n!==i.MAIN_THREAD_ID){Object(o.Bb)(e,s,n)||t.requestThreadInfoUpdate({chatId:s,threadId:n})}}),Object(s.b)("openSupportChat",(e,t)=>{const a=Object(o.xb)(e);t.openChat({id:a?a.id:-1}),a||(async()=>{const e=await Object(j.a)("fetchChat",{type:"support"});e&&t.openChat({id:e.chatId})})()}),Object(s.b)("openTipsChat",(e,t)=>{t.openChatByUsername({username:n.Ab})}),Object(s.b)("loadMoreChats",(e,t,a)=>{const{listType:s="active"}=a,n=e.chats.listIds[s];if(e.chats.isFullyLoaded[s])return;const c=n?n.map(t=>e.chats.byId[t]).filter(t=>Boolean(t&&t.lastMessage)&&!Object(o.M)(e,t.id)).sort((e,t)=>e.lastMessage.date-t.lastMessage.date)[0]:void 0;f(c?()=>v(s,c.id,c.lastMessage.date):()=>v(s))}),Object(s.b)("loadFullChat",(e,t,a)=>{const{chatId:s,force:n}=a,c=Object(o.f)(e,s);c&&(n?y(c):I(()=>y(c)))}),Object(s.b)("loadTopChats",()=>{p(()=>v("active"))}),Object(s.b)("requestChatUpdate",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);n&&Object(j.a)("requestChatUpdate",n)}),Object(s.b)("updateChatMutedState",(e,t,a)=>{const{chatId:s,isMuted:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatMutedState",{chat:c,isMuted:n})}),Object(s.b)("createChannel",(e,t,a)=>{const{title:n,about:c,photo:i,memberIds:d}=a;!async function(e,t,a,n){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const c=await Object(j.a)("createChannel",{title:e,about:a,users:t});if(!c)return;const{id:o,accessHash:i}=c;let d=Object(s.e)();d=Object(r.F)(d,o,c),d={...d,chatCreation:{...d.chatCreation,progress:c?l.a.Complete:l.a.Error}},Object(s.g)(d),Object(s.d)().openChat({id:o}),o&&i&&n&&await Object(j.a)("editChatPhoto",{chatId:o,accessHash:i,photo:n})}(n,d.map(t=>Object(o.Db)(e,t)).filter(Boolean),c,i)}),Object(s.b)("joinChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("joinChannel",{channelId:c,accessHash:r})}),Object(s.b)("leaveChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("leaveChannel",{channelId:c,accessHash:r})}),Object(s.b)("deleteChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("deleteChannel",{channelId:c,accessHash:r})}),Object(s.b)("createGroupChat",(e,t,a)=>{const{title:n,memberIds:c,photo:i}=a;!async function(e,t,a){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const n=await Object(j.a)("createGroupChat",{title:e,users:t});if(!n)return;const{id:c}=n;let o=Object(s.e)();o=Object(r.F)(o,c,n),o={...o,chatCreation:{...o.chatCreation,progress:n?l.a.Complete:l.a.Error}},Object(s.g)(o),Object(s.d)().openChat({id:c}),c&&a&&await Object(j.a)("editChatPhoto",{chatId:c,photo:a})}(n,c.map(t=>Object(o.Db)(e,t)).filter(Boolean),i)}),Object(s.b)("toggleChatPinned",(e,t,a)=>{const{id:s,folderId:c}=a,r=Object(o.f)(e,s);if(r)if(c){const t=Object(o.i)(e,c);if(t){const a=!Object(o.M)(e,s,c),{pinnedChatIds:n,includedChatIds:r}=t,i=a?[s,...n||[]]:(n||[]).filter(e=>e!==s),l=[s,...r];Object(j.a)("editChatFolder",{id:c,folderUpdate:{...t,pinnedChatIds:i,includedChatIds:l}})}}else{const t=Object(o.j)(e,s),a=Object(o.M)(e,s,"archived"===t?n.g:void 0);Object(j.a)("toggleChatPinned",{chat:r,shouldBePinned:!a})}}),Object(s.b)("toggleChatArchived",(e,t,a)=>{const{id:s}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleChatArchived",{chat:c,folderId:Object(m.gb)(c)?0:n.g})}),Object(s.b)("loadChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,...e}})}}()}),Object(s.b)("loadRecommendedChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchRecommendedChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,recommended:e}})}}()}),Object(s.b)("editChatFolder",(e,t,a)=>{const{id:s,folderUpdate:n}=a,c=Object(o.i)(e,s);c&&Object(j.a)("editChatFolder",{id:s,folderUpdate:{id:s,emoticon:c.emoticon,pinnedChatIds:c.pinnedChatIds,...n}})}),Object(s.b)("addChatFolder",(e,t,a)=>{const{folder:c}=a,{orderedIds:r}=e.chatFolders;!async function(e,t){const{id:a,description:n,...c}=e;if(await Object(j.a)("editChatFolder",{id:t+1,folderUpdate:{id:t+1,...c}}),!n)return;const r=Object(s.e)(),{recommended:o}=r.chatFolders;o&&Object(s.g)({...r,chatFolders:{...r.chatFolders,recommended:o.filter(({id:e})=>e!==a)}})}(c,r&&r.length?Math.max.apply(Math.max,r):n.g)}),Object(s.b)("deleteChatFolder",(e,t,a)=>{const{id:s}=a;Object(o.i)(e,s)&&async function(e){await Object(j.a)("deleteChatFolder",e)}(s)}),Object(s.b)("toggleChatUnread",(e,t,a)=>{const{id:s}=a,n=Object(o.f)(e,s);n&&(n.unreadCount?Object(j.a)("markMessageListRead",{chat:n,threadId:i.MAIN_THREAD_ID}):Object(j.a)("toggleDialogUnread",{chat:n,hasUnreadMark:!n.hasUnreadMark}))}),Object(s.b)("openTelegramLink",(e,t,a)=>{const{url:s}=a;let c=n.gb.exec(s);if(c){const e=c[1];(async()=>{const a=await Object(j.a)("openChatByInvite",e);a&&t.openChat({id:a.id})})()}else{c=n.hb.exec(s);const e=c[1],a=c[2]?Number(c[2]):void 0;C(t,e,a)}}),Object(s.b)("openChatByUsername",(e,t,a)=>{const{username:s}=a;C(t,s)}),Object(s.b)("togglePreHistoryHidden",(e,t,a)=>{const{chatId:s,isEnabled:n}=a;let c=Object(o.f)(e,s);c&&(async()=>{if(Object(m.hb)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}Object(j.a)("togglePreHistoryHidden",{chat:c,isEnabled:n})})()}),Object(s.b)("updateChatDefaultBannedRights",(e,t,a)=>{const{chatId:s,bannedRights:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatDefaultBannedRights",{chat:c,bannedRights:n})}),Object(s.b)("updateChatMemberBannedRights",(e,t,a)=>{const{chatId:n,userId:c,bannedRights:i}=a;let l=Object(o.f)(e,n);const d=Object(o.Db)(e,c);l&&d&&(async()=>{if(Object(m.hb)(l)){if(l=await Object(j.a)("migrateChat",l),!l)return;t.openChat({id:l.id})}await Object(j.a)("updateChatMemberBannedRights",{chat:l,user:d,bannedRights:i});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{members:b,kickedMembers:u}=a.fullInfo,h=!!i.viewMessages,O=!Object.keys(i).length;Object(s.g)(Object(r.F)(e,n,{fullInfo:{...a.fullInfo,...b&&h&&{members:b.filter(e=>e.userId!==c)},...b&&!h&&{members:b.map(e=>e.userId===c?{...e,bannedRights:i}:e)},...O&&u&&{kickedMembers:u.filter(e=>e.userId!==c)}}}))})()}),Object(s.b)("updateChatAdmin",(e,t,a)=>{const{chatId:n,userId:c,adminRights:i,customTitle:l}=a;let d=Object(o.f)(e,n);const b=Object(o.Db)(e,c);d&&b&&(async()=>{if(Object(m.hb)(d)){if(d=await Object(j.a)("migrateChat",d),!d)return;t.openChat({id:d.id})}await Object(j.a)("updateChatAdmin",{chat:d,user:b,adminRights:i,customTitle:l});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{adminMembers:u}=a.fullInfo,h=!Object.keys(i).length;Object(s.g)(Object(r.F)(e,n,{fullInfo:{...a.fullInfo,...u&&h&&{adminMembers:u.filter(e=>e.userId!==c)},...u&&!h&&{adminMembers:u.map(e=>e.userId===c?{...e,adminRights:i,customTitle:l}:e)}}}))})()}),Object(s.b)("updateChat",(e,t,a)=>{const{chatId:n,title:c,about:i,photo:d}=a,b=Object(o.f)(e,n);b&&(async()=>{Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.InProgress)),await Promise.all([b.title!==c?Object(j.a)("updateChatTitle",b,c):void 0,b.fullInfo&&b.fullInfo.about!==i?Object(j.a)("updateChatAbout",b,i):void 0,d?Object(j.a)("editChatPhoto",{chatId:n,accessHash:b.accessHash,photo:d}):void 0]),Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.Complete))})()}),Object(s.b)("toggleSignatures",(e,t,a)=>{const{chatId:s,isEnabled:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleSignatures",{chat:c,isEnabled:n})}),Object(s.b)("loadGroupsForDiscussion",()=>{(async()=>{const e=await Object(j.a)("fetchGroupsForDiscussion");if(!e)return;const t=e.reduce((e,t)=>(t&&(e[t.id]=t),e),{}),a=Object(r.c)(Object(s.e)(),t);Object(s.g)({...a,chats:{...a.chats,forDiscussionIds:Object.keys(t).map(Number)}})})()}),Object(s.b)("linkDiscussionGroup",(e,t,a)=>{const{channelId:s,chatId:n}=a,c=Object(o.f)(e,s);let r=Object(o.f)(e,n);c&&r&&(async()=>{if(Object(m.hb)(r)){if(r=await Object(j.a)("migrateChat",r),!r)return;t.openChat({id:r.id})}let{fullInfo:e}=r;if(!e){const t=await Object(j.a)("fetchFullChat",r);if(!t)return;e=t.fullInfo}e.isPreHistoryHidden&&await Object(j.a)("togglePreHistoryHidden",{chat:r,isEnabled:!1}),Object(j.a)("setDiscussionGroup",{channel:c,chat:r})})()}),Object(s.b)("unlinkDiscussionGroup",(e,t,a)=>{const{channelId:s}=a,n=Object(o.f)(e,s);if(!n)return;let c;n.fullInfo&&n.fullInfo.linkedChatId&&(c=Object(o.f)(e,n.fullInfo.linkedChatId)),(async()=>{await Object(j.a)("setDiscussionGroup",{channel:n}),c&&y(c)})()}),Object(s.b)("loadMoreMembers",e=>{(async()=>{const{chatId:t}=Object(o.y)(e)||{},a=t?Object(o.f)(e,t):void 0;if(!a||Object(m.hb)(a))return;const n=a.fullInfo&&a.fullInfo.members&&a.fullInfo.members.length||void 0,c=await Object(j.a)("fetchMembers",a.id,a.accessHash,"recent",n);if(!c)return;const{members:i,users:l}=c;i&&i.length&&(e=Object(s.e)(),e=Object(r.e)(e,Object(d.c)(l,"id")),e=Object(r.F)(e,a.id,{fullInfo:{...a.fullInfo,members:[...(a.fullInfo||{}).members||[],...i||[]]}}),Object(s.g)(e))})()});var w=a(143);const E=new Map;async function M(e,t,a,c,i=!1,b=!1){const u=e.id;let m;switch(c){case l.e.Backwards:m=void 0;break;case l.e.Around:m=-(Math.round(n.U/2)+1);break;case l.e.Forwards:m=-(n.U+1)}const h=await Object(j.a)("fetchMessages",{chat:Object(o.Ab)(Object(s.e)(),u,t),offsetId:a,addOffset:m,limit:n.U,threadId:t});if(!h)return;const{messages:O,users:g,chats:f,threadInfos:p,firstMessageId:I}=h,v=Object(d.c)(O,"id"),y=Object.keys(v).map(Number);let C=Object(s.e)();C=Object(r.b)(C,u,v),C=i?Object(r.bb)(C,u,t,y):Object(r.T)(C,u,t,y),C=Object(r.e)(C,Object(d.c)(g,"id")),C=Object(r.c)(C,Object(d.c)(f,"id")),C=Object(r.jb)(C,u,p),I&&(C=Object(r.v)(C,u,t,"firstMessageId",I));let w=Object(o.X)(C,u,t);const E=Object(o.db)(C,u,t);if(i&&w&&E&&Object(d.b)(w,E)&&(C=Object(r.T)(C,u,t,E),w=Object(o.X)(C,u,t),C=Object(r.v)(C,u,t,"outlyingIds",void 0),i=!1),!b){const e=i?E:w,{newViewportIds:s}=S(e,a,c);C=Object(r.x)(C,u,t,s)}Object(s.g)(C)}function S(e,t,a){const{length:s}=e,c=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex((a,s)=>a===t||at)}(e,t):-1,r=a===l.e.Backwards?c:c+1||s,o=r-n.U,i=r+n.U-1,d=e.slice(Math.max(0,o),i+1);let b,u;switch(a){case l.e.Backwards:b=r>0,u=o>=0;break;case l.e.Forwards:b=r0,u=d.length===n.U}return{newViewportIds:d,areSomeLocal:b,areAllLocal:u}}async function k(e){let t;const a=e.attachment?(e,n)=>{E.has(n)||(t=n,E.set(n,a));const c=Object(s.e)();Object(s.g)({...c,fileUploads:{byMessageLocalId:{...c.fileUploads.byMessageLocalId,[n]:{progress:e}}}})}:void 0;e.replyingTo&&await Object(g.f)();const n=Object(s.e)(),c=Object(o.y)(n);if(!c)return;const{threadId:r}=c;e.replyingTo||r===i.MAIN_THREAD_ID||(e.replyingTo=Object(o.Bb)(n,e.chat.id,r)),await Object(j.a)("sendMessage",e,a),a&&t&&E.delete(t)}Object(s.b)("loadViewportMessages",(e,t,a)=>{const{direction:s=l.e.Around,isBudgetPreload:c=!1}=a||{};let{chatId:i,threadId:d}=a||{};if(!i){const t=Object(o.y)(e);if(!t)return;i=t.chatId,d=t.threadId}const b=Object(o.f)(e,i);if(!b||b.isRestricted)return;const u=Object(o.Eb)(e,i,d),m=Object(o.X)(e,i,d),h=Object(o.db)(e,i,d);if(u&&u.length&&s!==l.e.Around){const a=s===l.e.Backwards?u[0]:u[u.length-1],n=Boolean(h),o=n?h:m,{newViewportIds:O,areSomeLocal:j,areAllLocal:g}=S(o,a,s);if(j&&(e=Object(r.x)(e,i,d,O)),async function(e,t,a,s,n,c,r,o){t||await M(n,c,o,r,a,s);s||(await Promise.resolve(),e.loadViewportMessages({chatId:n.id,threadId:c,direction:r,isBudgetPreload:!0}))}(t,g,n,c,b,d,s,a),c)return}else{const t=Object(o.H)(e,i)||Object(o.ib)(e,i,d),a=Boolean(t&&m&&!m.includes(t)),s=(a?h:m)||[],{newViewportIds:u,areSomeLocal:O,areAllLocal:j}=S(s,t,l.e.Around);O&&u.length>=n.U&&(e=Object(r.x)(e,i,d,u)),j||M(b,d,t,l.e.Around,a,c)}return e}),Object(s.b)("loadMessage",(e,t,a)=>{const{chatId:n,messageId:c,replyOriginForId:l}=a,b=Object(o.f)(e,n);b&&async function(e,t,a){const n=await Object(j.a)("fetchMessage",{chat:e,messageId:t});if(!n)return;if(n===i.MESSAGE_DELETED){if(a){let t=Object(s.e)();const n=Object(o.k)(t,e.id,a);t=Object(r.J)(t,e.id,a,{...n,replyToMessageId:void 0}),Object(s.g)(t)}return}let c=Object(s.e)();c=Object(r.J)(c,e.id,t,n.message),c=Object(r.e)(c,Object(d.c)(n.users,"id")),Object(s.g)(c)}(b,c,l)}),Object(s.b)("sendMessage",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:c,threadId:r,type:i}=s;if("scheduled"===i&&!a.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:a}};const l=Object(o.f)(e,c);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:c,threadId:r,value:!1});const b={...a,chat:l,replyingTo:Object(o.jb)(e,c,r),noWebPage:Object(o.bb)(e,c,r)},u=!a.attachments||a.attachments.length<=1,m=!u&&a.attachments&&a.attachments.length>1;if(u){const{attachments:e,...t}=b;k({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:a,...s}=b,c=Object(d.n)(a,n.K);for(let a=0;a0?o:void 0}),r.forEach(e=>{k({...s,attachment:e,groupedId:o})})}}else{const{text:e,entities:t,attachments:a,replyingTo:s,...n}=b;e&&k({...n,text:e,entities:t,replyingTo:s}),a.forEach(e=>{k({...n,attachment:e})})}}),Object(s.b)("editMessage",(e,t,a)=>{const{text:s,entities:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i,type:l}=c,d=Object(o.f)(e,r),b=Object(o.D)(e,r,i,l);d&&b&&(Object(j.a)("editMessage",{chat:d,message:b,text:s,entities:n}),t.setEditingId({messageId:void 0}))}),Object(s.b)("cancelSendingMessage",(e,t,a)=>{const{chatId:s,messageId:n}=a,c=Object(o.k)(e,s,n),r=c&&E.get(c.previousLocalId||c.id);r&&Object(j.b)(r),t.apiUpdate({"@type":"deleteMessages",ids:[n],chatId:s})}),Object(s.b)("saveDraft",(e,t,a)=>{const{chatId:s,threadId:n,draft:c}=a;if(!c)return;const{text:l,entities:d}=c,b=Object(o.f)(e,s);return n===i.MAIN_THREAD_ID&&Object(j.a)("saveDraft",{chat:b,text:l,entities:d,replyToMsgId:Object(o.jb)(e,s,n)}),Object(r.v)(e,s,n,"draft",c)}),Object(s.b)("clearDraft",(e,t,a)=>{const{chatId:s,threadId:n,localOnly:c}=a;if(!Object(o.B)(e,s,n))return;const l=Object(o.f)(e,s);return c||n!==i.MAIN_THREAD_ID||Object(j.a)("clearDraft",l),Object(r.v)(e,s,n,"draft",void 0)}),Object(s.b)("toggleMessageWebPage",(e,t,a)=>{const{chatId:s,threadId:n,noWebPage:c}=a;return Object(r.v)(e,s,n,"noWebPage",c)}),Object(s.b)("pinMessage",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageId:n,isUnpin:c,isOneSide:r,isSilent:i}=a;Object(j.a)("pinMessage",{chat:s,messageId:n,isUnpin:c,isOneSide:r,isSilent:i})}),Object(s.b)("unpinAllMessages",(e,t,a)=>{const n=Object(o.f)(e,a.chatId);n&&async function(e){await Object(j.a)("unpinAllMessages",{chat:e});let t=Object(s.e)();t=Object(r.v)(t,e.id,i.MAIN_THREAD_ID,"pinnedIds",[]),Object(s.g)(t)}(n)}),Object(s.b)("deleteMessages",(e,t,a)=>{const{messageIds:s,shouldDeleteForAll:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i}=c,l=Object(o.f)(e,r);Object(j.a)("deleteMessages",{chat:l,messageIds:s,shouldDeleteForAll:n});const d=Object(o.C)(e,r,i);s.includes(d)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteScheduledMessages",(e,t,a)=>{const{messageIds:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c}=n,r=Object(o.f)(e,c);Object(j.a)("deleteScheduledMessages",{chat:r,messageIds:s});const i=Object(o.E)(e,c);s.includes(i)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteHistory",(e,t,a)=>{const{chatId:s,maxId:n,shouldDeleteForAll:c}=a,r=Object(o.f)(e,s);r&&Object(j.a)("deleteHistory",{chat:r,shouldDeleteForAll:c,maxId:n})}),Object(s.b)("markMessageListRead",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:n,threadId:c}=s,r=Object(o.Ab)(e,n,c);if(!r)return;const{maxId:i}=a;Object(j.a)("markMessageListRead",{chat:r,threadId:c,maxId:i})}),Object(s.b)("markMessagesRead",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageIds:n}=a;Object(j.a)("markMessagesRead",{chat:s,messageIds:n})}),Object(s.b)("loadWebPagePreview",(e,t,a)=>{const{text:n}=a;!async function(e){const t=await Object(j.a)("fetchWebPagePreview",{message:e});Object(s.g)({...Object(s.e)(),webPagePreview:t})}(n)}),Object(s.b)("clearWebPagePreview",e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}}),Object(s.b)("sendPollVote",(e,t,a)=>{const{chatId:s,messageId:n,options:c}=a,r=Object(o.f)(e,s);r&&Object(j.a)("sendPollVote",{chat:r,messageId:n,options:c})}),Object(s.b)("loadPollOptionResults",(e,t,a)=>{const{chat:n,messageId:c,option:o,offset:i,limit:l,shouldResetVoters:b}=a;!async function(e,t,a,n,c,o){const i=await Object(j.a)("loadPollOptionResults",{chat:e,messageId:t,option:a,offset:n,limit:c});if(!i)return;let l=Object(s.e)();l=Object(r.e)(l,Object(d.c)(i.users,"id"));const{voters:b}=l.pollResults;Object(s.g)({...l,pollResults:{...l.pollResults,voters:{...b,[a]:[...!o&&b&&b[a]?b[a]:[],...i&&i.users.map(e=>e.id)].filter((e,t,a)=>a.indexOf(e)===t)},offsets:{...l.pollResults.offsets?l.pollResults.offsets:{},[a]:i.nextOffset||""}}})}(n,c,o,i,l,b)}),Object(s.b)("forwardMessages",e=>{const{fromChatId:t,messageIds:a,toChatId:n}=e.forwardMessages,c=t?Object(o.f)(e,t):void 0,r=n?Object(o.f)(e,n):void 0,i=t&&a?a.sort((e,t)=>e-t).map(a=>Object(o.k)(e,t,a)).filter(Boolean):void 0;c&&r&&i&&i.length&&function(e,t,a){Object(j.a)("forwardMessages",{fromChat:e,toChat:t,messages:a}),Object(s.g)({...Object(s.e)(),forwardMessages:{}})}(c,r,i)}),Object(s.b)("loadScheduledHistory",e=>{const t=Object(o.r)(e);if(!t)return;const{hash:a}=e.scheduledMessages.byChatId[t.id]||{};!async function(e,t){const a=await Object(j.a)("fetchScheduledHistory",{chat:e,hash:t});if(!a)return;const{hash:n,messages:c}=a,o=Object(d.c)(c,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.t)(b,e.id,o,n),b=Object(r.v)(b,e.id,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(b)}(t,a)}),Object(s.b)("sendScheduledMessages",(e,t,a)=>{const{chatId:s,id:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("sendScheduledMessages",{chat:c,ids:[n]})}),Object(s.b)("rescheduleMessage",(e,t,a)=>{const{chatId:s,messageId:n,scheduledAt:c}=a,r=Object(o.f)(e,s),i=r&&Object(o.mb)(e,r.id,n);r&&i&&Object(j.a)("rescheduleMessage",{chat:r,message:i,scheduledAt:c})}),Object(s.b)("requestThreadInfoUpdate",(e,t,a)=>{const{chatId:s,threadId:n}=a,c=Object(o.Ab)(e,s,n);c&&Object(j.a)("requestThreadInfoUpdate",{chat:c,threadId:n})}),Object(s.b)("loadPinnedMessages",(e,t,a)=>{const{chatId:n}=a,c=Object(o.f)(e,n);c&&async function(e){const t=await Object(j.a)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:a,chats:n,users:c}=t,o=Object(d.c)(a,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.b)(b,e.id,o),b=Object(r.v)(b,e.id,i.MAIN_THREAD_ID,"pinnedIds",l),b=Object(r.e)(b,Object(d.c)(c,"id")),b=Object(r.c)(b,Object(d.c)(n,"id")),Object(s.g)(b)}(c)}),Object(s.b)("loadMessageLink",(e,t,a)=>{const{messageId:s,chatId:n}=a,c=Object(o.f)(e,n),r=Object(o.k)(e,n,s);c&&r&&(async()=>{const e=await Object(j.a)("fetchMessageLink",{chat:c,message:r});e&&Object(w.c)(e.link)})()});var N=a(46);const P=Object(g.g)(e=>e(),500,!1);async function T(e,t){const a=await Object(j.a)("searchGifs",{query:e,offset:t});a&&Object(s.g)(Object(r.O)(Object(s.e)(),!t,a.gifs,a.nextOffset))}Object(s.b)("loadStickerSets",e=>{const{hash:t}=e.stickers.added||{};!async function(e=0){const t=await Object(j.a)("fetchStickerSets",{hash:e});if(!t)return;Object(s.g)(Object(r.gb)(Object(s.e)(),"added",t.hash,t.sets))}(t)}),Object(s.b)("loadAddedStickers",(e,t)=>{const{setIds:a}=e.stickers.added;a&&a.length&&(async()=>{for(let e=0;e0&&await Object(g.e)(500)})()}),Object(s.b)("loadRecentStickers",e=>{const{hash:t}=e.stickers.recent||{};!async function(e=0){const t=await Object(j.a)("fetchRecentStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,recent:t}})}(t)}),Object(s.b)("loadFavoriteStickers",e=>{const{hash:t}=e.stickers.favorite||{};!async function(e=0){const t=await Object(j.a)("fetchFavoriteStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,favorite:t}})}(t)}),Object(s.b)("loadFeaturedStickers",e=>{const{hash:t}=e.stickers.featured||{};!async function(e=0){const t=await Object(j.a)("fetchFeaturedStickers",{hash:e});if(!t)return;Object(s.g)(Object(r.gb)(Object(s.e)(),"featured",t.hash,t.sets))}(t)}),Object(s.b)("loadStickers",(e,t,a)=>{const{stickerSetId:n}=a;let{stickerSetAccessHash:c}=a;if(!c){const t=Object(o.ub)(e,n);if(!t)return;c=t.accessHash}!async function(e,t){const a=await Object(j.a)("fetchStickers",{stickerSetId:e,accessHash:t});if(!a)return;const{set:n,stickers:c,packs:o}=a;let i=Object(s.e)();i=Object(r.fb)(i,n.id,{...n,stickers:c,packs:o});const l=i.stickers.forEmoji.emoji;l&&o[l]&&(i=Object(r.n)(i));Object(s.g)(i)}(n,c)}),Object(s.b)("loadAnimatedEmojis",()=>{!async function(){const e=await Object(j.a)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:a}=e;Object(s.g)(Object(r.p)(Object(s.e)(),{...t,stickers:a}))}()}),Object(s.b)("loadSavedGifs",e=>{const{hash:t}=e.gifs.saved;!async function(e=0){const t=await Object(j.a)("fetchSavedGifs",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,gifs:{...a.gifs,saved:t}})}(t)}),Object(s.b)("faveSticker",(e,t,a)=>{const{sticker:s}=a;s&&Object(j.a)("faveSticker",{sticker:s})}),Object(s.b)("unfaveSticker",(e,t,a)=>{const{sticker:n}=a;n&&function(e){const t=Object(s.e)();Object(s.g)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter(({id:t})=>t!==e.id)}}}),Object(j.a)("faveSticker",{sticker:e,unfave:!0})}(n)}),Object(s.b)("toggleStickerSet",(e,t,a)=>{const{stickerSetId:s}=a,n=Object(o.ub)(e,s);if(!n)return;const{accessHash:c,installedDate:r}=n;Object(j.a)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:s,accessHash:c})}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:n}=a;n&&P(()=>{!async function(e,t=0){const a=await Object(j.a)("searchStickers",{query:e,hash:t});if(!a)return;const n=Object(s.e)(),{setsById:c,added:o}=n.stickers,i=a.sets.map(({id:e})=>e);o.setIds&&o.setIds.forEach(t=>{if(!i.includes(t)){const{title:a}=c[t]||{};a&&Object(N.a)(a,e)&&i.unshift(t)}});Object(s.g)(Object(r.gb)(n,"search",a.hash,a.sets,i))}(n)})}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;"string"==typeof s&&P(()=>{T(s)})}),Object(s.b)("searchMoreGifs",e=>{const{query:t,offset:a}=e.gifs.search;"string"==typeof t&&P(()=>{T(t,a)})}),Object(s.b)("loadStickersForEmoji",(e,t,a)=>{const{emoji:n}=a,{hash:c}=e.stickers.forEmoji;P(()=>{!async function(e,t=0){let a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,forEmoji:{...a.stickers.forEmoji,emoji:e}}});const n=await Object(j.a)("fetchStickersForEmoji",{emoji:e,hash:t});if(a=Object(s.e)(),!n||a.stickers.forEmoji.emoji!==e)return;a=Object(r.hb)(a,e,n.stickers,n.hash),Object(s.g)(a)}(n,c)})}),Object(s.b)("clearStickersForEmoji",e=>({...e,stickers:{...e.stickers,forEmoji:{}}}));var A=a(30);const x=Object(g.g)(e=>e(),500,!1);async function R(e="",t,a,c,i,l){let b;if(c){const s=await Object(j.a)("searchMessagesLocal",{chatOrUser:c,query:e,type:t,limit:n.x,offsetId:a,minDate:l,maxDate:i});if(s){const{messages:e,users:t,totalCount:a,nextOffsetId:n}=s;b={messages:e,users:t,chats:[],totalCount:a,nextRate:n}}}else b=await Object(j.a)("searchMessagesGlobal",{query:e,offsetRate:a,limit:n.x,type:t,maxDate:i,minDate:l});let u=Object(s.e)();const m=Object(o.t)(u);if(!b||""!==e&&e!==m)return void Object(s.g)(Object(r.R)(u,{messages:!1}));const{messages:h,users:O,chats:g,totalCount:f,nextRate:p}=b;g.length&&(u=Object(r.c)(u,Object(d.c)(g,"id"))),O.length&&(u=Object(r.e)(u,Object(d.c)(O,"id"))),h.length&&(u=Object(r.d)(u,h)),u=Object(r.S)(u,h,f,t,p),Object(s.g)(u)}Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{chatId:n}=e.globalSearch,{query:c}=a;c&&!n&&x(()=>{!async function(e){const t=await Object(j.a)("searchChats",{query:e});let a=Object(s.e)();const n=Object(o.t)(a);if(!t||!n||e!==n)return void Object(s.g)(Object(r.R)(a,{chats:!1}));const{localChats:c,localUsers:i,globalChats:l,globalUsers:b}=t;(c.length||l.length)&&(a=Object(r.c)(a,Object(d.c)([...c,...l],"id")));(i.length||b.length)&&(a=Object(r.e)(a,Object(d.c)([...i,...b],"id")));a=Object(r.R)(a,{chats:!1}),a=Object(r.P)(a,{localResults:{chatIds:c.map(({id:e})=>e),userIds:i.map(({id:e})=>e)},globalResults:{...a.globalSearch.globalResults,chatIds:b.map(({id:e})=>e),userIds:l.map(({id:e})=>e)}}),Object(s.g)(a)}(c)})}),Object(s.b)("setGlobalSearchDate",(e,t,a)=>{const{date:n}=a,c=n?Object(A.m)(n):n,i=Object(r.P)(e,{date:n,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});Object(s.g)(i);const{chatId:l}=e.globalSearch;R("","text",void 0,l?Object(o.f)(e,l):void 0,c,n)}),Object(s.b)("searchMessagesGlobal",(e,t,a)=>{const{query:s,resultsByType:n,chatId:c,date:r}=e.globalSearch,i=r?Object(A.m)(r):r,{type:l}=a,{nextOffsetId:d}=n&&n[l]||{};R(s,l,d,c?Object(o.f)(e,c):void 0,i,r)}),Object(s.b)("searchTextMessagesLocal",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},c=t?Object(o.f)(e,t):void 0,l=Object(o.A)(e);if(!c||!l||!a)return;const{query:b,results:u}=l,m=u?u.nextOffsetId:void 0;let h;if(a!==i.MAIN_THREAD_ID){const s=Object(o.zb)(e,t,a);h=s?s.topMessageId:void 0}!async function(e,t,a,c,i){const l=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:"text",query:c,topMessageId:a,limit:n.W,offsetId:i});if(!l)return;const{messages:b,users:u,totalCount:m,nextOffsetId:h}=l,O=Object(d.c)(b,"id"),g=Object.keys(O).map(Number);let f=Object(s.e)();const p=Object(o.A)(f);if(!p||c&&c!==p.query)return;f=Object(r.b)(f,e.id,O),f=Object(r.e)(f,Object(d.c)(u,"id")),f=Object(r.X)(f,e.id,t,g,m,h),Object(s.g)(f)}(c,a,h,b,m)}),Object(s.b)("searchMediaMessagesLocal",e=>{const t=Object(o.w)(e),a=t?e.users.byId[t]||e.chats.byId[t]:void 0,c=Object(o.v)(e);if(!a||!c)return;const{currentType:i,resultsByType:l}=c,b=i&&l&&l[i],u=b?b.nextOffsetId:void 0;i&&async function(e,t,a){const c=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:t,limit:n.mb,offsetId:a});if(!c)return;const{messages:i,users:l,totalCount:b,nextOffsetId:u}=c,m=Object(d.c)(i,"id"),h=Object.keys(m).map(Number);let O=Object(s.e)();if(!Object(o.v)(O))return;O=Object(r.b)(O,e.id,m),O=Object(r.e)(O,Object(d.c)(l,"id")),O=Object(r.U)(O,e.id,t,h,b,u),Object(s.g)(O)}(a,i,u)}),Object(s.b)("searchMessagesByDate",(e,t,a)=>{const{timestamp:n}=a,{chatId:c}=Object(o.y)(e)||{};if(!c)return;const r=Object(o.f)(e,c);r&&async function(e,t){const a=await Object(j.a)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});if(!a)return;Object(s.d)().focusMessage({chatId:e.id,messageId:a})}(r,n)}),Object(s.b)("checkPublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};if(!n)return;if(e.management.progress===l.f.InProgress)return;const{username:c}=a;(async()=>{e=Object(r.Z)(e,l.f.InProgress),e=Object(r.Y)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e);const t=await Object(j.a)("checkChatUsername",{username:c});e=Object(s.e)(),e=Object(r.Z)(e,t?l.f.Complete:l.f.Error),e=Object(r.Y)(e,n,{isUsernameAvailable:t}),Object(s.g)(e)})()}),Object(s.b)("updatePublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};let c=n&&Object(o.f)(e,n);if(!n||!c)return;const{username:i}=a;(async()=>{if(e=Object(r.Z)(e,l.f.InProgress),Object(s.g)(e),Object(m.hb)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}const a=await Object(j.a)("setChatUsername",{chat:c,username:i});e=Object(s.e)(),e=Object(r.Z)(e,a?l.f.Complete:l.f.Error),e=Object(r.Y)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e)})()}),Object(s.b)("updatePrivateLink",e=>{const{chatId:t}=Object(o.y)(e)||{},a=t&&Object(o.f)(e,t);t&&a&&Object(j.a)("updatePrivateLink",{chat:a})});var L=a(32);async function F(){const e=await Object(j.a)("fetchChats",{limit:n.i,archived:!0,withPinned:!0});if(!e)return;let t=Object(s.e)();t=Object(r.mb)(t,Object(d.c)(e.users,"id")),t=Object(r.K)(t,Object(d.c)(e.chats,"id")),t=Object(r.q)(t,"archived",e.chatIds),t=Object(r.H)(t,"archived",e),Object(s.g)(t)}async function D(){let e=Object(s.e)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:a}=e.contactList||{};if(!(a&&a.length||t&&t.length))return;const n=[...t||[],...a||[]].map(t=>Object(o.Db)(e,t)).filter(Boolean),c=await Object(j.a)("fetchUsers",{users:n});c&&(e=Object(s.e)(),e=Object(r.mb)(e,Object(d.c)(c,"id")),Object(s.g)(e))}Object(s.b)("sync",(e,t)=>{!async function(e){n.o&&console.log(">>> START SYNC");Object(L.a)(),await Object(j.a)("fetchCurrentUser");const t=await async function(){const e=await Object(j.a)("fetchChats",{limit:n.i,withPinned:!0});if(!e)return;let t=Object(s.e)();const{recentlyFoundChatIds:a}=t.globalSearch,{userIds:c}=t.contactList||{},{currentUserId:l}=t,b=[...a||[],...c||[],...l?[l]:[]],u=b.map(e=>Object(o.Db)(t,e)).filter(Boolean),h=b.map(e=>Object(o.f)(t,e)).filter(Boolean),{chatId:O}=Object(o.y)(t)||{};if(O){const e=Object(o.f)(t,O);if(e&&!b.includes(O)&&h.push(e),Object(m.kb)(O)){const e=Object(o.Db)(t,O);e&&!b.includes(O)&&u.push(e)}}u.push(...e.users),h.push(...e.chats),t=Object(r.r)(t,Object(d.c)(h,"id")),t=Object(r.q)(t,"active",e.chatIds),t={...t,chats:{...t.chats}},t=Object(r.H)(t,"active",e),Object.keys(e.draftsById).map(Number).forEach(a=>{t=Object(r.v)(t,a,i.MAIN_THREAD_ID,"draft",e.draftsById[a])}),Object.keys(e.replyingToById).map(Number).forEach(a=>{t=Object(r.v)(t,a,i.MAIN_THREAD_ID,"replyingToId",e.replyingToById[a])}),Object(s.g)(t),O&&!t.chats.byId[O]&&Object(s.d)().openChat({id:void 0});return u}();await async function(e){let t=!1,a=e||[],c=Object(s.e)();const{chatId:l}=Object(o.y)(c)||{},b=Object.keys(c.messages.byChatId).map(Number).reduce((e,t)=>{const a=Object(o.B)(c,t,i.MAIN_THREAD_ID);return a?{...e,[t]:a}:e},{});if(l){const e=await(u=c.chats.byId[l],Object(j.a)("fetchMessages",{chat:u,threadId:i.MAIN_THREAD_ID,offsetId:u.lastReadInboxMessageId,addOffset:-(Math.round(n.U/2)+1),limit:n.U}));c=Object(s.e)();const{chatId:b}=Object(o.y)(c)||{};if(e&&b===l){const s=c.messages.byChatId[l],n=Object(d.c)(e.messages,"id"),o=Object.keys(n).map(Number);c={...c,messages:{...c.messages,byChatId:{[l]:{byId:n,threadsById:{[i.MAIN_THREAD_ID]:{...s&&s.threadsById[i.MAIN_THREAD_ID],listedIds:o,viewportIds:o,outlyingIds:void 0}}}}}},c=Object(r.K)(c,Object(d.c)(e.chats,"id")),c=Object(r.jb)(c,l,e.threadInfos),t=!0,a=Array.prototype.concat(a,e.users)}}var u;t||(c={...c,messages:{...c.messages,byChatId:{}}});Object.keys(b).map(Number).forEach(e=>{c=Object(r.v)(c,e,i.MAIN_THREAD_ID,"draft",b[e])}),e?c=Object(r.w)(c,Object(d.c)(a,"id")):a&&(c=Object(r.mb)(c,Object(d.c)(a,"id")));Object(s.g)(c)}(t),Object(s.g)({...Object(s.e)(),lastSyncTime:Date.now()}),n.o&&console.log(">>> FINISH SYNC");e()}(t.afterSync)}),Object(s.b)("afterSync",(e,t)=>{!async function(e){n.o&&console.log(">>> START AFTER-SYNC");e.loadFavoriteStickers(),await Promise.all([D(),F()]),await Object(j.a)("fetchCurrentUser"),n.o&&console.log(">>> FINISH AFTER-SYNC")}(t)});const B=Object(g.a)(e=>e(),500,!1,!0);function U(e,{visibility:t,allowedIds:a,deniedIds:s}){const{users:{byId:n},chats:{byId:c}}=e,r={visibility:t};let o,i;const l=e=>{if(!Object(m.kb)(e))return;const{id:t,accessHash:a}=n[e]||{};return t?{id:t,accessHash:a}:void 0},d=e=>{if(Object(m.kb)(e))return;const t=c[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(o=a.map(l).filter(Boolean),i=a.map(d).filter(Boolean),o.length>0&&(r.allowedUsers=o),i.length>0&&(r.allowedChats=i)),"everybody"!==t&&"contacts"!==t||(o=s.map(l).filter(Boolean),i=s.map(d).filter(Boolean),o.length>0&&(r.blockedUsers=o),i.length>0&&(r.blockedChats=i)),r}Object(s.b)("loadFullUser",(e,t,a)=>{const{userId:s}=a,n=Object(o.Db)(e,s);if(!n)return;const{id:c,accessHash:r}=n;B(()=>Object(j.a)("fetchFullUser",{id:c,accessHash:r}))}),Object(s.b)("loadUser",(e,t,a)=>{const{userId:n}=a,c=Object(o.Db)(e,n);c&&(async()=>{const t=await Object(j.a)("fetchUsers",{users:[c]});t&&(e=Object(s.e)(),e=Object(r.mb)(e,Object(d.c)(t,"id")),Object(s.g)(e))})()}),Object(s.b)("loadTopUsers",e=>{const{hash:t,lastRequestedAt:a}=e.topPeers;(!a||Date.now()-a>6e4)&&async function(e){const t=await Object(j.a)("fetchTopUsers",{hash:e});if(!t)return;const{hash:a,ids:n,users:c}=t;let o=Object(s.e)();o=Object(r.e)(o,Object(d.c)(c,"id")),o={...o,topPeers:{...o.topPeers,hash:a,userIds:n,lastRequestedAt:Date.now()}},Object(s.g)(o)}(t)}),Object(s.b)("loadContactList",e=>{const{hash:t}=e.contactList||{};!async function(e){const t=await Object(j.a)("fetchContactList",{hash:e});if(!t)return;let a=Object(r.e)(Object(s.e)(),Object(d.c)(t.users,"id"));a=Object(r.c)(a,Object(d.c)(t.chats,"id"));const n=e=>e.lastName||e.firstName||"",c=new Intl.Collator("en-US"),o=t.users.sort((e,t)=>c.compare(n(e),n(t))).filter(e=>!e.isSelf);Object(s.g)({...a,contactList:{hash:t.hash,userIds:o.map(e=>e.id)}})}(t)}),Object(s.b)("loadCurrentUser",()=>{Object(j.a)("fetchCurrentUser")}),Object(s.b)("updateContact",(e,t,a)=>{const{userId:n,isMuted:c,firstName:i,lastName:d}=a;!async function(e,t,a,n){const c=Object(s.e)(),i=Object(o.Db)(c,e);if(!i)return;Object(s.d)().updateChatMutedState({chatId:e,isMuted:t}),Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.InProgress));await Object(j.a)("updateContact",{phone:i.phoneNumber,firstName:a,lastName:n})&&Object(s.g)(Object(r.lb)(Object(s.e)(),i.id,{firstName:a,lastName:n}));Object(s.g)(Object(r.Z)(Object(s.e)(),l.f.Complete))}(n,c,i,d)}),Object(s.b)("deleteUser",(e,t,a)=>{const{userId:n}=a;!async function(e){const t=Object(s.e)(),a=Object(o.Db)(t,e);if(!a)return;const{id:n,accessHash:c}=a;await Object(j.a)("deleteUser",{id:n,accessHash:c})}(n)}),Object(s.b)("loadProfilePhotos",(e,t,a)=>{const{profileId:n}=a,c=Object(m.kb)(n),i=c?Object(o.Db)(e,n):void 0,l=c?void 0:Object(o.f)(e,n);(async()=>{const e=await Object(j.a)("fetchProfilePhotos",i,l);if(!e||!e.photos)return;let t=Object(s.e)();c?t=Object(r.lb)(t,n,{photos:e.photos}):(t=Object(r.e)(t,Object(d.c)(e.users,"id")),t=Object(r.F)(t,n,{photos:e.photos})),Object(s.g)(t)})()}),Object(s.b)("clickInlineButton",(e,t,a)=>{const{button:c}=a;switch(c.type){case"command":t.sendBotCommand({command:c.value});break;case"url":c.value.match(n.gb)||c.value.match(n.hb)?t.openTelegramLink({url:c.value}):window.open(c.value);break;case"callback":{const t=Object(o.r)(e);if(!t)return;!async function(e,t,a){const n=await Object(j.a)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:a});if(!n||!n.message)return;const{message:c,alert:r}=n;r?Object(s.d)().showError({error:{message:c}}):Object(s.d)().showNotification({message:c})}(t,c.messageId,c.value);break}case"requestPoll":t.openPollModal();break;case"buy":{const a=Object(o.r)(e),{messageId:s,value:n}=c;if(!a)return;n?t.getReceipt({receiptMessageId:n,chatId:a.id,messageId:s}):(t.getPaymentForm({messageId:s}),t.setInvoiceMessageInfo(Object(o.k)(e,a.id,s)),t.openPaymentModal({messageId:s}));break}}}),Object(s.b)("sendBotCommand",(e,t,a)=>{const{command:s}=a,{currentUserId:n}=e,c=Object(o.r)(e);n&&c&&async function(e,t,a){await Object(j.a)("sendMessage",{chat:e,text:a})}(c,0,s)}),Object(s.b)("updateProfile",(e,t,a)=>{const{photo:n,firstName:c,lastName:i,bio:d,username:b}=a;(async()=>{const{currentUserId:t}=e;if(t){if(Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.InProgress}}),n&&await Object(j.a)("updateProfilePhoto",n),c||i||d){if(await Object(j.a)("updateProfile",{firstName:c,lastName:i,about:d})){e=Object(s.e)();const a=t&&Object(o.Db)(e,t);a&&Object(s.g)(Object(r.lb)(e,a.id,{firstName:c,lastName:i,fullInfo:{...a.fullInfo,bio:d}}))}}if(b){await Object(j.a)("updateUsername",b)&&t&&Object(s.g)(Object(r.lb)(Object(s.e)(),t,{username:b}))}Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.Complete}})}})()}),Object(s.b)("checkUsername",(e,t,a)=>{const{username:n}=a;(async()=>{if(e.profileEdit&&e.profileEdit.progress===l.j.InProgress)return;Object(s.g)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:l.j.Idle,isUsernameAvailable:void 0}});const t=await Object(j.a)("checkUsername",n);e=Object(s.e)(),Object(s.g)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()}),Object(s.b)("loadWallpapers",()=>{(async()=>{const e=await Object(j.a)("fetchWallpapers",0);if(!e)return;const t=Object(s.e)();Object(s.g)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()}),Object(s.b)("uploadWallpaper",(e,t,a)=>{const n=a,c=URL.createObjectURL(n);Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[{slug:l.n,document:{fileName:"",size:n.size,mimeType:n.type,previewBlobUrl:c}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await Object(j.a)("uploadWallpaper",n);if(!t)return;const{wallpaper:a}=t;if(!(e=Object(s.e)()).settings.loadedWallpapers)return;const r=e.settings.loadedWallpapers[0];if(!r||r.slug!==l.n)return;const o={...a,document:{...a.document,previewBlobUrl:c}};Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[o,...e.settings.loadedWallpapers.slice(1)]}})})()}),Object(s.b)("loadBlockedContacts",()=>{(async()=>{const e=await Object(j.a)("fetchBlockedContacts");if(!e)return;let t=Object(s.e)();e.users&&e.users.length&&(t=Object(r.e)(t,Object(d.c)(e.users,"id"))),e.chats&&e.chats.length&&(t=Object(r.K)(t,Object(d.c)(e.chats,"id"))),t={...t,blocked:{...t.blocked,ids:[...t.blocked.ids||[],...e.blockedIds],totalCount:e.totalCount}},Object(s.g)(t)})()}),Object(s.b)("blockContact",(e,t,a)=>{const{contactId:n}=a;(async()=>{if(!await Object(j.a)("blockContact",n))return;const e=Object(s.e)();Object(s.g)(Object(r.a)(e,n))})()}),Object(s.b)("unblockContact",(e,t,a)=>{const{contactId:n}=a;let c;if(Object(m.kb)(n)){const t=Object(o.Db)(e,n);if(!t)return;c=t.accessHash}(async()=>{if(!await Object(j.a)("unblockContact",n,c))return;const e=Object(s.e)();Object(s.g)(Object(r.o)(e,n))})()}),Object(s.b)("loadAuthorizations",()=>{(async()=>{const e=await Object(j.a)("fetchAuthorizations");e&&Object(s.g)({...Object(s.e)(),activeSessions:e})})()}),Object(s.b)("terminateAuthorization",(e,t,a)=>{const{hash:n}=a;(async()=>{if(!await Object(j.a)("terminateAuthorization",n))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.hash!==n)})})()}),Object(s.b)("terminateAllAuthorizations",()=>{(async()=>{if(!await Object(j.a)("terminateAllAuthorizations"))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.isCurrent)})})()}),Object(s.b)("loadNotificationsSettings",()=>{(async()=>{const e=await Object(j.a)("loadNotificationsSettings");e&&Object(s.g)(Object(r.u)(Object(s.e)(),e))})()}),Object(s.b)("updateNotificationSettings",(e,t,a)=>{const{peerType:n,isSilent:c,isShowPreviews:o}=a;(async()=>{await Object(j.a)("updateNotificationSettings",n,{isSilent:c,isShowPreviews:o})&&Object(s.g)(Object(r.ab)(Object(s.e)(),n,c,o))})()}),Object(s.b)("updateContactSignUpNotification",(e,t,a)=>{const{isSilent:n}=a;(async()=>{await Object(j.a)("updateContactSignUpNotification",n)&&Object(s.g)(Object(r.u)(Object(s.e)(),{hasContactJoinedNotifications:!n}))})()}),Object(s.b)("loadLanguages",()=>{(async()=>{const e=await Object(j.a)("fetchLanguages");e&&Object(s.g)(Object(r.u)(Object(s.e)(),{languages:e}))})()}),Object(s.b)("loadPrivacySettings",()=>{(async()=>{const[e,t,a,n,c]=await Promise.all([Object(j.a)("fetchPrivacySettings","phoneNumber"),Object(j.a)("fetchPrivacySettings","lastSeen"),Object(j.a)("fetchPrivacySettings","profilePhoto"),Object(j.a)("fetchPrivacySettings","forwards"),Object(j.a)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&a&&n&&c))return;const r=Object(s.e)();r.settings.privacy.phoneNumber=e,r.settings.privacy.lastSeen=t,r.settings.privacy.profilePhoto=a,r.settings.privacy.forwards=n,r.settings.privacy.chatInvite=c,Object(s.g)(r)})()}),Object(s.b)("setPrivacyVisibility",(e,t,a)=>{const{privacyKey:n,visibility:c}=a,{privacy:{[n]:r}}=e.settings;if(!r)return;const o=U(e,{visibility:c,allowedIds:[...r.allowUserIds,...r.allowChatIds],deniedIds:[...r.blockUserIds,...r.blockChatIds]});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,o);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("setPrivacySettings",(e,t,a)=>{const{privacyKey:n,isAllowList:c,contactsIds:r}=a,{privacy:{[n]:o}}=e.settings;if(!o)return;const i=U(e,{visibility:o.visibility,allowedIds:c?r:[...o.allowUserIds,...o.allowChatIds],deniedIds:c?[...o.blockUserIds,...o.blockChatIds]:r});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,i);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("loadPasswordInfo",()=>{(async()=>{const e=await Object(j.a)("getPasswordInfo");if(!e)return;let t=Object(s.e)();t=Object(r.u)(t,{hasPassword:e.hasPassword}),t=Object(r.kb)(t,{hint:e.hint}),Object(s.g)(t)})()}),Object(s.b)("checkPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("checkPassword",n);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("clearPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("clearPassword",n);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("updatePassword",(e,t,a)=>{const{currentPassword:n,password:c,hint:o,email:i,onSuccess:l}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updatePassword",n,c,o,i);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1})),e&&l()})()}),Object(s.b)("updateRecoveryEmail",(e,t,a)=>{const{currentPassword:n,email:c,onSuccess:o}=a;Object(s.g)(Object(r.kb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updateRecoveryEmail",n,c);Object(s.g)(Object(r.kb)(Object(s.e)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&o()})()}),Object(s.b)("provideTwoFaEmailCode",(e,t,a)=>{const{code:s}=a;Object(j.a)("provideRecoveryEmailCode",s)}),Object(s.b)("clearTwoFaError",e=>Object(r.kb)(e,{error:void 0}));var H=a(54);Object(s.b)("validateRequestedInfo",(e,t,a)=>{const{requestInfo:n,saveInfo:c}=a,i=Object(o.eb)(e);i&&async function(e,t,a){const n=await Object(j.a)("validateRequestedInfo",{messageId:e,requestInfo:t,shouldSave:a});if(!n)return;const{id:c,shippingOptions:o}=n;if(!c)return;let i=Object(r.C)(Object(s.e)(),c);o?(i=Object(r.eb)(i,o),i=Object(r.A)(i,l.i.Shipping)):i=Object(r.A)(i,l.i.PaymentInfo);Object(s.g)(i)}(i,n,c)}),Object(s.b)("getPaymentForm",(e,t,a)=>{const{messageId:n}=a;n&&async function(e){const t=await Object(j.a)("getPaymentForm",{messageId:e});if(!t)return;let a=Object(r.z)(Object(s.e)(),t),n=l.i.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(n=l.i.ShippingInfo);a=Object(r.A)(a,n),Object(s.g)(a)}(n)}),Object(s.b)("getReceipt",(e,t,a)=>{const{receiptMessageId:n,chatId:c,messageId:i}=a;i&&n&&c&&async function(e,t,a){const n=await Object(j.a)("getReceipt",t);if(!n)return;let c=Object(s.e)();const i=Object(o.k)(c,a,e);c=Object(r.B)(c,n,i),Object(s.g)(c)}(i,n,c)}),Object(s.b)("clearPaymentError",e=>{Object(s.g)({...e,payment:{...e.payment,error:void 0}})}),Object(s.b)("clearReceipt",e=>{Object(s.g)({...e,payment:{...e.payment,receipt:void 0}})}),Object(s.b)("sendCredentialsInfo",(e,t,a)=>{const n=Object(o.hb)(e);if(!n)return;const{credentials:c}=a,{data:i}=c;!async function(e,t){const a=function(e){const t=Object.keys(e).map(t=>`${t}=${e[t]}`).join("&");return t.length>0?"?"+t:""}({"card[number]":e.cardNumber,"card[exp_month]":e.expiryMonth,"card[exp_year]":e.expiryYear,"card[cvc]":e.cvv,"card[address_zip]":e.zip,"card[address_country]":e.country}),n=await fetch("https://api.stripe.com/v1/tokens"+a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:"Bearer "+t}}),c=await n.json();if(c.error){const e=Object(H.b)(c.error),t=Object(s.e)();return void Object(s.g)({...t,payment:{...t.payment,error:{...e}}})}let o=Object(r.D)(Object(s.e)(),{type:c.type,id:c.id});o=Object(r.A)(o,l.i.Checkout),Object(s.g)(o)}(i,n)}),Object(s.b)("sendPaymentForm",(e,t,a)=>{const{shippingOptionId:n,saveCredentials:c}=a,i=Object(o.eb)(e),l=Object(o.fb)(e),d=Object(o.hb)(e),b=Object(o.wb)(e);i&&d&&async function(e,t,a,n){if(await Object(j.a)("sendPaymentForm",{messageId:e,credentials:t,requestedInfoId:a,shippingOptionId:n})){const e=Object(r.g)(Object(s.e)());Object(s.g)(Object(r.h)(e))}}(i,{save:c,data:b},l,n)}),Object(s.b)("setPaymentStep",(e,t,a={})=>Object(r.A)(e,a.step||l.i.ShippingInfo)),Object(s.b)("setInvoiceMessageInfo",(e,t,a)=>Object(r.y)(e,a));a(76);Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateChat":Object(o.L)(e,a.id)||t.loadTopChats(),Object(s.g)(Object(r.F)(e,a.id,a.chat,a.newProfilePhoto));break;case"updateChatJoin":{const n=Object(o.j)(e,a.id);if(!n)break;e=Object(r.G)(e,n,[a.id]),e=Object(r.F)(e,a.id,{isNotJoined:!1}),Object(s.g)(e);const c=Object(o.f)(e,a.id);c&&t.requestChatUpdate({chatId:c.id});break}case"updateChatLeave":{const t=Object(o.j)(e,a.id);if(!t)break;const{[t]:n}=e.chats.listIds;n&&(e=Object(r.q)(e,t,n.filter(e=>e!==a.id))),e=Object(r.F)(e,a.id,{isNotJoined:!0}),Object(s.g)(e);break}case"updateChatInbox":Object(s.g)(Object(r.F)(e,a.id,a.chat));break;case"updateChatTypingStatus":{const{id:t,typingStatus:n}=a;Object(s.g)(Object(r.F)(e,t,{typingStatus:n})),setTimeout(()=>{const e=Object(s.e)(),a=Object(o.f)(e,t);a&&n&&a.typingStatus&&a.typingStatus.timestamp===n.timestamp&&Object(s.g)(Object(r.F)(e,t,{typingStatus:void 0}))},6e3);break}case"newMessage":{const{message:n}=a,{chatId:c}=Object(o.y)(e)||{};if(n.senderId===e.currentUserId&&!n.isFromScheduled)return;const i=Object(o.f)(e,a.chatId);if(!i)return;a.chatId===c?setTimeout(()=>{t.requestChatUpdate({chatId:a.chatId})},1e3):Object(s.g)(Object(r.F)(e,a.chatId,{unreadCount:i.unreadCount?i.unreadCount+1:1,...a.message.hasUnreadMention&&{unreadMentionsCount:i.unreadMentionsCount?i.unreadMentionsCount+1:1}}));break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:n}=a;if(!1!==n.hasUnreadMention)return;t.forEach(t=>{const s="channelId"in a?a.channelId:Object(o.p)(e,t),n=Object(o.f)(e,s);n&&n.unreadMentionsCount&&(e=Object(r.F)(e,s,{unreadMentionsCount:n.unreadMentionsCount-1}))}),Object(s.g)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=a,n=e.chats.byId[a.id];if(!n)return;Object(s.g)(Object(r.F)(e,a.id,{fullInfo:{...n.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:c}=a,r=c===n.g?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},Object(s.g)(e);break}case"updateChatPinned":{const{id:t,isPinned:c}=a,r=Object(o.j)(e,t);if(r){const{[r]:a}=e.chats.orderedPinnedIds;let s=a||[];if(c){if(!s.includes(t)){if("active"===r&&s.length>=n.J){const t=e.chats.listIds.active;s=s.filter(e=>t&&t.includes(e))}s=[t,...s]}}else s=s.filter(e=>e!==t);e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:s.length?s:void 0}}}}Object(s.g)(e);break}case"updateChatListType":{const{id:t,folderId:n}=a;Object(s.g)(Object(r.I)(e,t,n));break}case"updateChatFolder":{const{id:t,folder:n}=a,{byId:c,orderedIds:r}=e.chatFolders,o=n?{...c,[t]:n}:Object(d.l)(c,Object.keys(c).map(Number).filter(e=>e!==t)),i=n?r&&r.includes(t)?r:[...r||[],t]:r?r.filter(e=>e!==t):void 0;Object(s.g)({...e,chatFolders:{...e.chatFolders,byId:o,orderedIds:i}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{const t=e.chats.byId[a.id],{replacedMembers:n,addedMember:c,deletedMemberId:o}=a;if(!t)return;let i=!1,l=t.fullInfo&&t.fullInfo.members?[...t.fullInfo.members]:[];if(n)l=n,i=!0;else if(c)l.length&&l.some(e=>e.userId===c.userId)||(l.push(c),i=!0);else if(l.length&&o){const e=l.findIndex(e=>e.userId===o);e>-1&&(l.slice(e,1),i=!0)}if(i){const n=l.filter(({isOwner:e,isAdmin:t})=>e||t);Object(s.g)(Object(r.F)(e,a.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:n}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:n}=a,c=e.chats.byId[t];c&&c.photos&&Object(s.g)(Object(r.F)(e,t,{photos:c.photos.filter(e=>!n.includes(e.id))}));break}}});function q(e,t,a,s,n=!1){const c=n?Object(o.mb)(e,t,a):Object(o.k)(e,t,a);if(c&&s.content){const{photo:e,video:t,sticker:a,document:n}=Object(m.v)(c);e&&s.content.photo?(s.content.photo.blobUrl=e.blobUrl,s.content.photo.thumbnail=e.thumbnail):t&&s.content.video?s.content.video.blobUrl=t.blobUrl:a&&s.content.sticker?s.content.sticker.isPreloadedGlobally=a.isPreloadedGlobally:n&&s.content.document&&(s.content.document.previewBlobUrl=n.previewBlobUrl)}return n?Object(r.cb)(e,t,a,s):Object(r.J)(e,t,a,s)}function G(e,t){const{id:a,chatId:s}=t;e=Object(r.T)(e,s,i.MAIN_THREAD_ID,[a]),Object(o.W)(e,s,i.MAIN_THREAD_ID)&&(e=Object(r.f)(e,s,i.MAIN_THREAD_ID,a));const{threadInfo:n,firstMessageId:c}=Object(o.yb)(e,s,t)||{};return!c&&Object(m.rb)(t)||n&&(e=Object(r.T)(e,s,n.threadId,[a]),Object(o.W)(e,s,n.threadId)&&(e=Object(r.f)(e,s,n.threadId,a),c||(e=Object(r.v)(e,s,n.threadId,"firstMessageId",t.id)),n.lastMessageId||(e=Object(r.v)(e,s,n.threadId,"threadInfo",{...n,lastMessageId:t.id})))),e}function _(e,t,a,s=!1){const{chats:n}=e,c=n.byId[t]&&n.byId[t].lastMessage;if(c&&!s){if(!(c.id===a.id||c.id===a.previousLocalId||a.id>c.id))return e}return Object(r.F)(e,t,{lastMessage:a})}function z(e,t){const a=Object(o.m)(e,t),s=Object(o.X)(e,t,i.MAIN_THREAD_ID);if(!a||!s)return;let n=s.length;for(;n--;){const e=a[s[n]];if(!e.isDeleting)return e}}function W(e,t,a,n){if(e){t.forEach(t=>{const a=z(n=Object(r.J)(n,e,t,{isDeleting:!0}),e);a&&(n=_(n,e,a,!0))}),Object(s.g)(n),a.requestChatUpdate({chatId:e});const c=[];return t.forEach(t=>{const a=Object(o.k)(n,e,t);if(!a)return;const{threadInfo:s}=Object(o.yb)(n,e,a)||{};s&&c.push(s.threadId)}),Object(d.o)(c).forEach(t=>{a.requestThreadInfoUpdate({chatId:e,threadId:t})}),void setTimeout(()=>{Object(s.g)(Object(r.i)(Object(s.e)(),e,t))},350)}const c=[];t.forEach(e=>{const t=Object(o.p)(n,e);if(t){c.push(t);const a=z(n=Object(r.J)(n,t,e,{isDeleting:!0}),t);a&&(n=_(n,t,a,!0)),setTimeout(()=>{Object(s.g)(Object(r.i)(Object(s.e)(),t,[e]))},350)}}),Object(s.g)(n),Object(d.o)(c).forEach(e=>{a.requestChatUpdate({chatId:e})})}Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"newMessage":{const{chatId:n,id:c,message:i}=a;e=G(e=q(e,n,c,i),i),i.threadInfo&&(e=Object(r.ib)(e,i.threadInfo.chatId,i.threadInfo.threadId,i.threadInfo)),Object(s.g)(e);const l=Object(o.k)(e,n,c);if(Object(o.a)(e,n,i)){if(i.isOutgoing&&(!i.content||!i.content.action)){const a=Object(o.y)(e);a&&t.focusMessage({chatId:n,threadId:a.threadId,messageId:i.id,noHighlight:!0})}const{threadInfo:a}=Object(o.yb)(e,n,i)||{};a&&t.requestThreadInfoUpdate({chatId:n,threadId:a.threadId}),i.isOutgoing||setTimeout(()=>{Object(s.g)(_(Object(s.e)(),n,l))},350)}else Object(s.g)(_(Object(s.e)(),n,l));Object(o.L)(e,n)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:n,message:c}=a;e=q(e,t,n,c,!0);const l=Object(o.lb)(e,t)||[];e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",Object(d.o)([...l,n])),Object(s.g)(e);break}case"updateMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.k)(e,t,n))return;e=q(e,t,n,c);const i=Object(o.k)(e,t,n);c.threadInfo&&(e=Object(r.ib)(e,c.threadInfo.chatId,c.threadInfo.threadId,c.threadInfo)),e=_(e,t,i),Object(s.g)(e);break}case"updateScheduledMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.mb)(e,t,n))return;e=q(e,t,n,c,!0);const l=Object.keys(Object(o.nb)(e,t)||{}).map(Number).sort((e,t)=>t-e);e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(e);break}case"updateMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a;e=G(e,c);const i=Object(o.k)(e,t,n);e=Object(r.i)(e,t,[n]),c.isScheduled&&(e=Object(r.j)(e,t,[n])),e=Object(r.J)(e,t,c.id,{...i,...c,previousLocalId:n});const l=Object(o.k)(e,t,c.id);e=_(e,t,l),Object(s.g)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a,l=Object(o.lb)(e,t)||[];e=Object(r.v)(e,t,i.MAIN_THREAD_ID,"scheduledIds",[...l,c.id]);const d=Object(o.mb)(e,t,n);e=Object(r.j)(e,t,[n]),e=Object(r.cb)(e,t,c.id,{...d,...c,previousLocalId:n}),Object(s.g)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:n,messageIds:c}=a,l=Object(o.gb)(e,t)||[],d=n?[...l,...c]:l.filter(e=>!c.includes(e));Object(s.g)(Object(r.v)(e,t,i.MAIN_THREAD_ID,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:n,threadInfo:c}=a,i={...Object(o.zb)(e,t,n),...c};if(!i.threadId)return;e=Object(r.ib)(e,t,n,i),Object(s.g)(e);break}case"resetMessages":{const{id:n}=a,c=Object(o.m)(e,n);c&&!Object(m.kb)(n)&&(e=Object(r.i)(e,n,Object.keys(c).map(Number)),Object(s.g)(e),t.loadFullChat({chatId:n,force:!0}));break}case"deleteMessages":{const{ids:s,chatId:n}=a;W(n,s,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:n}=a;!function(e,t,a,n){if(!e)return;t.forEach(t=>{n=Object(r.cb)(n,e,t,{isDeleting:!0})}),Object(s.g)(n),setTimeout(()=>{n=Object(r.j)(Object(s.e)(),e,t);const a=Object(o.nb)(n,e);n=Object(r.v)(n,e,i.MAIN_THREAD_ID,"scheduledIds",Object.keys(a||{}).map(Number)),Object(s.g)(n)},350)}(n,t,0,e);break}case"deleteHistory":{const{chatId:s}=a;W(s,Object.keys(e.messages.byChatId[s].byId).map(Number),t,e);break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:n}=a;t.forEach(t=>{const a=Object(o.p)(e,t);a&&(e=Object(r.J)(e,a,t,n))}),Object(s.g)(e);break}case"updateChannelMessages":{const{channelId:t,ids:n,messageUpdate:c}=a;n.forEach(a=>{e=Object(r.J)(e,t,a,c)}),Object(s.g)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:n}=a,c=Object(o.l)(e,t);if(c&&c.content.poll){const t={...c.content.poll,...n},{results:a}=t.results||{};if(a&&!a.some(e=>e.isChosen)){const{results:e}=c.content.poll.results,s=e&&e.filter(e=>e.isChosen);s&&s.forEach(e=>{const s=a.findIndex(t=>t.option===e.option);s>=0&&(t.results.results[s].isChosen=!0)})}Object(s.g)(Object(r.J)(e,c.chatId,c.id,{content:{...c.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:n,options:c}=a,i=Object(o.l)(e,t);if(!i||!i.content.poll||!i.content.poll.results)break;const{poll:l}=i.content,{recentVoterIds:d,totalVoters:b,results:u}=l.results,m=d?[...d]:[],h=b?b+1:1,O=u?[...u]:[];m.push(n),c.forEach(t=>{const a=O.find(e=>e.option===t),s=O.findIndex(e=>e.option===t),c=a?{...a}:{option:t,votersCount:0};c.votersCount+=1,n===e.currentUserId&&(c.isChosen=!0),s?O[s]=c:O.push(c)}),Object(s.g)(Object(r.J)(e,i.chatId,i.id,{content:{...i.content,poll:{...l,results:{...l.results,recentVoterIds:m,totalVoters:h,results:O}}}}));break}}});const V=Object(g.g)((function(){let e=Object(s.e)();$.forEach(([t,a])=>{e=Object(r.lb)(e,t,{status:a})}),Object(s.g)(e),$=[]}),3e3,!0);let $=[];Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"deleteUser":return Object(r.k)(e,a.id);case"updateUser":return Object(r.lb)(e,a.id,a.user);case"updateUserStatus":return s=a.userId,n=a.status,$.push([s,n]),void V();case"updateUserFullInfo":{const{id:t,fullInfo:s}=a,n=e.users.byId[t];if(!n)return;return Object(r.lb)(e,t,{fullInfo:{...n.fullInfo,...s}})}}var s,n}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateStickerSet":return Object(r.fb)(e,a.id,a.stickerSet)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updatePeerBlocked":return a.isBlocked?Object(r.a)(Object(s.e)(),a.id):Object(r.o)(Object(s.e)(),a.id);case"updateResetContactList":Object(s.g)({...Object(s.e)(),contactList:{hash:0,userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[a.key]=a.rules}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateNotifySettings":return Object(r.ab)(e,a.peerType,a.isSilent,a.isShowPreviews)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:a.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:a.message}}}});var Q=a(43),K=a(8),Y=a(29),J=a(121),Z=a(42),X=a(100),ee=a(66),te=a(94),ae=a(56),se=a(34),ne=a(25),ce=a(144),re=a(130);a(186);var oe=Object(c.h)(({id:e,name:t,value:a,label:s,checked:n=!1,disabled:r,inactive:o,onChange:i,onCheck:l})=>{const d=Object(c.m)(e=>{i&&i(e),l&&l(e.currentTarget.checked)},[i,l]),b=Object(K.a)("Switcher",r&&"disabled",o&&"inactive");return c.a.createElement("label",{className:b,title:s},c.a.createElement("input",{type:"checkbox",id:e,name:t,value:a,checked:n,disabled:r,onChange:d}),c.a.createElement("span",{className:"widget"}))});a(187);const ie=[0,1,2];var le=Object(c.h)(Object(s.h)(e=>{const{query:t,fetchingStatus:a,chatId:s,date:n}=e.globalSearch,{currentUserId:c}=e,{byId:r}=e.chats,{theme:o,animationLevel:i}=e.settings.byKey;return{searchQuery:t,isLoading:!!a&&Boolean(a.chats||a.messages),currentUserId:c,chatsById:r,globalSearchChatId:s,searchDate:n,theme:o,animationLevel:i}},(e,t)=>Object(d.l)(t,["openChat","openTipsChat","setGlobalSearchDate","setGlobalSearchChatId","setSettingOption"]))(({content:e,contactsFilter:t,onSearchQuery:a,onSelectSettings:s,onSelectContacts:r,onSelectArchived:o,setGlobalSearchChatId:i,onReset:d,searchQuery:b,isLoading:u,currentUserId:O,globalSearchChatId:j,searchDate:g,theme:f,animationLevel:p,chatsById:I,openChat:v,openTipsChat:y,setGlobalSearchDate:C,setSettingOption:w})=>{const E=e===l.d.ChatList,M={date:void 0},S={id:void 0},k=Object(c.p)(()=>g?Object(A.a)(new Date(1e3*g)):void 0,[g]),N=Object(c.p)(()=>E&&I?Object.values(I).reduce((e,t)=>Object(m.gb)(t)&&t.unreadCount?e+1:e,0):0,[E,I]),P=Object(c.p)(()=>({onTrigger:e,isOpen:t})=>c.a.createElement(ne.a,{round:!0,ripple:E&&!h.f,size:"smaller",color:"translucent",className:t?"active":"",onClick:E?e:()=>d(),ariaLabel:E?"Open menu":"Return to chat list"},c.a.createElement("div",{className:Object(K.a)("animated-menu-icon",!E&&"state-back")})),[E,d]),T=Object(c.m)(()=>{b||a("")},[b,a]),x=Object(c.m)(()=>{v({id:O})},[O,v]),R=Object(c.m)(e=>{e.stopPropagation();const t="light"===f?"dark":"light",a="dark"===t;w({theme:t,customBackground:a?n.m:void 0,patternColor:a?n.n:n.s}),Object(ee.a)(t,p>0)},[p,w,f]),L=Object(c.m)(e=>{e.stopPropagation();const t=0===p?2:0;ie.forEach((e,a)=>{document.body.classList.toggle("animation-level-"+a,t===a)}),w({animationLevel:t})},[p,w]),F=Object(te.a)(),D=Boolean(j)||e===l.d.GlobalSearch||e===l.d.Contacts,B=e===l.d.Contacts?F("SearchFriends"):F("Search");return c.a.createElement("div",{className:"LeftMainHeader"},c.a.createElement("div",{id:"LeftMainHeader",className:"left-header"},c.a.createElement(ae.a,{trigger:P,footer:n.f},c.a.createElement(se.a,{icon:"saved-messages",onClick:x},F("SavedMessages")),c.a.createElement(se.a,{icon:"archive",onClick:o},c.a.createElement("span",{className:"menu-item-name"},F("ArchivedChats")),N>0&&c.a.createElement("div",{className:"archived-badge"},N)),c.a.createElement(se.a,{icon:"user",onClick:r},F("Contacts")),c.a.createElement(se.a,{icon:"settings",onClick:s},F("Settings")),c.a.createElement(se.a,{icon:"darkmode",onClick:R},c.a.createElement("span",{className:"menu-item-name"},"Dark Mode"),c.a.createElement(oe,{id:"darkmode",label:"Toggle Dark Mode",checked:"dark"===f})),c.a.createElement(se.a,{icon:"animations",onClick:L},c.a.createElement("span",{className:"menu-item-name capitalize"},F("Appearance.Animations").toLowerCase()),c.a.createElement(oe,{id:"animations",label:"Toggle Animations",checked:p>0})),c.a.createElement(se.a,{icon:"help",onClick:y},"Telegram Features"),c.a.createElement(se.a,{icon:"bug",href:n.w},"Report Bug")),c.a.createElement(ce.a,{inputId:"telegram-search-input",className:j||g?"with-picker-item":"",value:t||b,focused:D,isLoading:u,placeholder:B,canClose:Boolean(j||g),onChange:a,onReset:d,onFocus:T},k&&c.a.createElement(re.a,{icon:"calendar",title:k,canClose:!0,isMinimized:Boolean(j),className:"search-date",onClick:C,clickArg:M}),j&&c.a.createElement(re.a,{chatOrUserId:j,onClick:i,canClose:!0,clickArg:S}))))})),de=a(20);a(188);var be=Object(s.h)(e=>Object(d.l)(e,["connectionState"]))(({connectionState:e})=>{const t=Object(te.a)();return"connectionStateConnecting"===e&&c.a.createElement("div",{id:"ConnectionState"},c.a.createElement(de.a,{color:"black"}),c.a.createElement("div",{className:"state-text"},t("WaitingForNetwork")))}),ue=a(122),me=a(103),he=a(31),Oe=(e,t,a)=>{const s=Object(c.q)(),n=(e=>Object(c.p)(()=>Object(g.g)(e=>e(),e),[e]))(t),r=Object(he.a)();return Object(me.a)(()=>{let t=!0;n(()=>{s.current=e(),t||r()}),t=!1},a),s.current},je=a(158),ge=a(178);var fe=Object(c.h)(Object(s.h)(e=>{const{chats:{byId:t},users:{byId:a},chatFolders:{byId:s,orderedIds:n},lastSyncTime:c}=e;return{chatsById:t,usersById:a,chatFoldersById:s,orderedFolderIds:n,lastSyncTime:c}},(e,t)=>Object(d.l)(t,["loadChatFolders"]))(({chatsById:e,usersById:t,chatFoldersById:a,orderedFolderIds:s,lastSyncTime:n,loadChatFolders:r})=>{const o=Object(c.q)(null),[i,l]=Object(c.r)(0);Object(c.n)(()=>{n&&r()},[n,r]);const b=Object(c.p)(()=>s?s.map(e=>a[e]||{}).filter(Boolean):void 0,[a,s]),u=Oe(()=>{if(!b||!b.length)return;const a=Object.keys(e).map(Number),s=b.map(s=>{const{unreadDialogsCount:n,hasActiveDialogs:c}=Object(m.p)(e,t,s,a)||{};return{id:s.id,badgeCount:n,isBadgeActive:c}});return Object(d.c)(s,"id")},3e3,[b,e,t]),O=Object(c.p)(()=>{if(b&&b.length)return[{title:"All"},...b.map(e=>({title:e.title,...u&&u[e.id]}))]},[b,u]),j=Object(c.m)(e=>{l(e)},[]);Object(c.n)(()=>{O&&O.length&&i>=O.length&&l(0)},[i,O]),Object(c.n)(()=>{if(o.current&&h.k&&O&&O.length)return Object(ue.b)(o.current,{onSwipe:(e,t)=>{t===ue.a.Left?l(Math.min(i+1,O.length-1)):t===ue.a.Right&&l(Math.max(0,i-1))}})},[i,O]);const{shouldRender:g,transitionClassNames:f}=Object(Y.a)(!s,void 0,!0),p=Object(te.a)();function I(){const e=Object.values(a).find(({title:e})=>e===O[i].title);return e&&0!==i?c.a.createElement(ge.a,{folderType:"folder",folderId:e.id,noChatsText:p("FilterNoChatsToDisplay")}):c.a.createElement(ge.a,{folderType:"all"})}return c.a.createElement("div",{className:"ChatFolders"},O&&O.length?c.a.createElement(je.a,{tabs:O,activeTab:i,onSwitchTab:j}):g?c.a.createElement("div",{className:Object(K.a)("tabs-placeholder",f)}):void 0,c.a.createElement(X.a,{ref:o,name:"slide",activeKey:i,renderCount:O?O.length:void 0},I))})),pe=a(12),Ie=a(17),ve=a(16);var ye=e=>{const t=Object(Ie.a)(pe.a.Extra,"LeftSearch");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Ce=e=>{const t=Object(Ie.a)(pe.a.Extra,"ContactList");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)},we=a(47);a(200);let Ee;var Me=Object(c.h)(({isShown:e,onNewPrivateChat:t,onNewChannel:a,onNewGroup:s})=>{const[n,r]=Object(c.r)(!1);Object(c.n)(()=>{e||r(!1)},[e]);const o=Object(te.a)(),i=Object(K.a)("NewChatButton",e&&"revealed",n&&"menu-is-open"),l=Object(c.m)(()=>{Ee&&(clearTimeout(Ee),Ee=void 0)},[]),d=Object(c.m)(()=>{Ee&&(clearTimeout(Ee),Ee=void 0),Ee=window.setTimeout(()=>{r(!1)},750)},[]);return c.a.createElement("div",{className:i,onMouseEnter:l,onMouseLeave:d},c.a.createElement(ne.a,{round:!0,color:"primary",className:n?"active":"",onClick:()=>{r(!n)},ariaLabel:n?"Close":"Create new chat",tabIndex:-1},c.a.createElement("i",{className:"icon-new-chat-filled"}),c.a.createElement("i",{className:"icon-close"})),c.a.createElement(we.a,{isOpen:n,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},c.a.createElement(se.a,{icon:"channel",onClick:a},o("NewChannel")),c.a.createElement(se.a,{icon:"group",onClick:s},o("NewGroup")),c.a.createElement(se.a,{icon:"user",onClick:t},"New Private Chat")))});a(201);const Se=Object.keys(l.d).length/2;let ke;var Ne=Object(c.h)(({content:e,searchQuery:t,searchDate:a,contactsFilter:s,onSearchQuery:n,onContentChange:r,onReset:o})=>{const[i,d]=Object(c.r)(h.k),b=Object(c.q)(!1),u=Object(c.m)(()=>{r(l.d.Settings)},[r]),m=Object(c.m)(()=>{r(l.d.Contacts)},[r]),O=Object(c.m)(()=>{r(l.d.NewChannelStep1)},[r]),j=Object(c.m)(()=>{r(l.d.NewGroupStep1)},[r]),g=Object(c.m)(()=>{r(l.d.Archived)},[r]),f=Object(c.m)(()=>{e===l.d.ChatList&&(b.current=!0,d(!0))},[e]),p=Object(c.m)(()=>{b.current=!1,ke&&(clearTimeout(ke),ke=void 0),ke=window.setTimeout(()=>{b.current||d(!1)},250)},[]);return Object(c.n)(()=>{let t;return e!==l.d.ChatList?t=window.setTimeout(()=>{d(!1)},250):(b.current||h.k)&&d(!0),()=>{t&&(clearTimeout(t),t=void 0)}},[e]),c.a.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.k?void 0:f,onMouseLeave:h.k?void 0:p},c.a.createElement(le,{content:e,contactsFilter:s,onSearchQuery:n,onSelectSettings:u,onSelectContacts:m,onSelectArchived:g,onReset:o}),c.a.createElement(be,null),c.a.createElement(X.a,{name:"zoom-fade",renderCount:Se,activeKey:e},()=>{switch(e){case l.d.ChatList:return c.a.createElement(fe,null);case l.d.GlobalSearch:return c.a.createElement(ye,{searchQuery:t,searchDate:a,onReset:o});case l.d.Contacts:return c.a.createElement(Ce,{filter:s});default:return}}),c.a.createElement(Me,{isShown:i,onNewPrivateChat:m,onNewChannel:O,onNewGroup:j}))});var Pe=e=>{const t=Object(Ie.a)(pe.a.Extra,"Settings");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Te=e=>{const t=Object(Ie.a)(pe.a.Extra,"NewChat");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var Ae,xe=e=>{const t=Object(Ie.a)(pe.a.Extra,"ArchivedChats");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};a(202);!function(e){e[e.Main=0]="Main",e[e.Settings=1]="Settings",e[e.Archived=2]="Archived",e[e.NewGroup=3]="NewGroup",e[e.NewChannel=4]="NewChannel"}(Ae||(Ae={}));const Re=Object.keys(Ae).length/2;var Le=Object(c.h)(Object(s.h)(e=>{const{query:t,date:a}=e.globalSearch;return{searchQuery:t,searchDate:a}},(e,t)=>Object(d.l)(t,["setGlobalSearchQuery","setGlobalSearchChatId","resetChatCreation","setGlobalSearchDate","loadPasswordInfo","clearTwoFaError"]))(({searchQuery:e,searchDate:t,setGlobalSearchQuery:a,setGlobalSearchChatId:s,resetChatCreation:n,setGlobalSearchDate:r,loadPasswordInfo:o,clearTwoFaError:i})=>{const[d,b]=Object(c.r)(l.d.ChatList),[u,m]=Object(c.r)(l.m.Main),[O,j]=Object(c.r)(""),[g,f]=Object(c.r)(0);let p=Ae.Main;switch(d){case l.d.Archived:p=Ae.Archived;break;case l.d.Settings:p=Ae.Settings;break;case l.d.NewChannelStep1:case l.d.NewChannelStep2:p=Ae.NewChannel;break;case l.d.NewGroupStep1:case l.d.NewGroupStep2:p=Ae.NewGroup}const I=Object(c.m)(e=>{if(d!==l.d.NewGroupStep2||e){if(d===l.d.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(d===l.d.Settings)switch(u){case l.m.EditProfile:case l.m.Folders:case l.m.General:case l.m.Notifications:case l.m.Privacy:case l.m.Language:return void m(l.m.Main);case l.m.GeneralChatBackground:return void m(l.m.General);case l.m.GeneralChatBackgroundColor:return void m(l.m.GeneralChatBackground);case l.m.PrivacyPhoneNumber:case l.m.PrivacyLastSeen:case l.m.PrivacyProfilePhoto:case l.m.PrivacyForwarding:case l.m.PrivacyGroupChats:case l.m.PrivacyActiveSessions:case l.m.PrivacyBlockedUsers:case l.m.TwoFaDisabled:case l.m.TwoFaEnabled:case l.m.TwoFaCongratulations:return void m(l.m.Privacy);case l.m.PrivacyPhoneNumberAllowedContacts:case l.m.PrivacyPhoneNumberDeniedContacts:return void m(l.m.PrivacyPhoneNumber);case l.m.PrivacyLastSeenAllowedContacts:case l.m.PrivacyLastSeenDeniedContacts:return void m(l.m.PrivacyLastSeen);case l.m.PrivacyProfilePhotoAllowedContacts:case l.m.PrivacyProfilePhotoDeniedContacts:return void m(l.m.PrivacyProfilePhoto);case l.m.PrivacyForwardingAllowedContacts:case l.m.PrivacyForwardingDeniedContacts:return void m(l.m.PrivacyForwarding);case l.m.PrivacyGroupChatsAllowedContacts:case l.m.PrivacyGroupChatsDeniedContacts:return void m(l.m.PrivacyGroupChats);case l.m.TwoFaNewPassword:return void m(l.m.TwoFaDisabled);case l.m.TwoFaNewPasswordConfirm:return void m(l.m.TwoFaNewPassword);case l.m.TwoFaNewPasswordHint:return void m(l.m.TwoFaNewPasswordConfirm);case l.m.TwoFaNewPasswordEmail:return void m(l.m.TwoFaNewPasswordHint);case l.m.TwoFaNewPasswordEmailCode:return void m(l.m.TwoFaNewPasswordEmail);case l.m.TwoFaChangePasswordCurrent:case l.m.TwoFaTurnOff:case l.m.TwoFaRecoveryEmailCurrentPassword:return void m(l.m.TwoFaEnabled);case l.m.TwoFaChangePasswordNew:return void m(l.m.TwoFaChangePasswordCurrent);case l.m.TwoFaChangePasswordConfirm:return void m(l.m.TwoFaChangePasswordNew);case l.m.TwoFaChangePasswordHint:return void m(l.m.TwoFaChangePasswordConfirm);case l.m.TwoFaRecoveryEmail:return void m(l.m.TwoFaRecoveryEmailCurrentPassword);case l.m.TwoFaRecoveryEmailCode:return void m(l.m.TwoFaRecoveryEmail);case l.m.FoldersCreateFolder:case l.m.FoldersEditFolder:return void m(l.m.Folders)}b(l.d.ChatList),j(""),a({query:""}),r({date:void 0}),s({id:void 0}),n(),setTimeout(()=>{f(Date.now())},250)}else b(l.d.NewGroupStep1)},[d,a,s,r,n,u]),v=Object(c.m)(t=>{d!==l.d.Contacts?(b(l.d.GlobalSearch),t!==e&&a({query:t})):j(t)},[d,a,e]);return Object(c.n)(()=>d!==l.d.ChatList?Object(Z.a)(()=>I()):void 0,[d,I]),Object(c.n)(()=>{i(),u===l.m.Privacy&&o()},[i,o,u]),c.a.createElement(X.a,{id:"LeftColumn",name:h.f?"slide-layers":"push-slide",renderCount:Re,activeKey:p},()=>{switch(p){case Ae.Archived:return c.a.createElement(xe,{onReset:I});case Ae.Settings:return c.a.createElement(Pe,{currentScreen:u,onScreenSelect:m,onReset:I});case Ae.NewChannel:return c.a.createElement(Te,{key:g,isChannel:!0,content:d,onContentChange:b,onReset:I});case Ae.NewGroup:return c.a.createElement(Te,{key:g,content:d,onContentChange:b,onReset:I});default:return c.a.createElement(Ne,{content:d,searchQuery:e,searchDate:t,contactsFilter:O,onContentChange:b,onSearchQuery:v,onReset:I})}})})),Fe=a(128),De=a(13),Be=a(49);var Ue=()=>{const[e,t]=Object(c.r)(Be.a.get());return Object(c.n)(()=>{const e=Object(g.g)(()=>{t(Be.a.get())},250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),e},He=a(38);function qe(e,t){const a=Object(He.a)(e,!0),s=Object(c.q)(),n=Object(he.a)(),r=null!=e;return r&&s.current&&(clearTimeout(s.current),s.current=void 0),Object(me.a)(()=>{t&&!r&&a&&!s.current&&(s.current=window.setTimeout(()=>{s.current=void 0,n()},t))},[e]),r||t&&!s.current?e:a}function Ge(e,t){const a=e<=n.cb?16:32,s=function(e){if(e>n.Z){const t=Math.min(Math.max(.25*e,288),424),a=Math.min(.25*e,424);return Math.min(e-t-a,728)}if(e>n.Y){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,728)}if(e>728)return 728;return e}(e),c=e<=n.cb?54:64,r=t?s-a-c:s-a,o=e>n.cb?Math.min(s-a,512):s-a,i=o/r,l=r/o;return{composerHiddenScale:i,toolbarHiddenScale:l,composerTranslateX:t?c/2*l:0,toolbarTranslateX:t?c/2*-1*i:0,unpinHiddenScale:o/258,toolbarForUnpinHiddenScale:258/o}}var _e=a(134),ze=a(132);function We(e,t=!1,a=!1){const s=Object(He.a)(e,t);return a||null!=e?e:s}var Ve=a(44),$e=a(98),Qe=a(114);var Ke=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"HeaderMenuContainer",!t);return a?c.a.createElement(a,e):void 0};var Ye=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=Boolean(n&&Object(m.ib)(n));if(n&&n.isRestricted)return{noMenu:!0};const r=Object(o.O)(e,t),l="thread"===s&&a===i.MAIN_THREAD_ID,d="thread"===s&&a!==i.MAIN_THREAD_ID,b=Object(o.V)(e),u=Boolean(Object(o.K)(e,t)),O=Boolean(l&&n&&(c||Object(m.mb)(n))&&n.isNotJoined),j=l||d,g=l&&!r&&!O,f=!Object(o.R)(e),p=l&&!O;return{noMenu:!(h.f&&O||h.f&&j||g||f||p),isChannel:c,isRightColumnShown:b,canStartBot:u,canSubscribe:O,canSearch:j,canMute:g,canSelect:f,canLeave:p}},(e,t)=>Object(d.l)(t,["joinChannel","sendBotCommand","openLocalTextSearch"]))(({chatId:e,threadId:t,noMenu:a,isChannel:s,canStartBot:n,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,isRightColumnShown:b,joinChannel:u,sendBotCommand:m,openLocalTextSearch:O})=>{const j=Object(c.q)(null),[g,f]=Object(c.r)(!1),[p,I]=Object(c.r)(void 0),v=Object(c.m)(()=>{f(!0);const e=j.current.getBoundingClientRect();I({x:e.right,y:e.bottom})},[]),y=Object(c.m)(()=>{f(!1)},[]),C=Object(c.m)(()=>{I(void 0)},[]),w=Object(c.m)(()=>{u({chatId:e})},[u,e]),E=Object(c.m)(()=>{m({command:"/start"})},[m]),M=Object(c.m)(()=>{if(O(),h.f){document.querySelector("#MobileSearch input").focus()}else setTimeout(()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()},400)},[O]),S=Object(te.a)();return c.a.createElement("div",{className:"HeaderActions"},!h.f&&r&&c.a.createElement(ne.a,{size:"tiny",ripple:!0,fluid:!0,onClick:w},S(s?"Subscribe":"Join Group")),!h.f&&n&&c.a.createElement(ne.a,{size:"tiny",ripple:!0,fluid:!0,onClick:E},S("Start")),!h.f&&o&&c.a.createElement(ne.a,{round:!0,ripple:b,color:"translucent",size:"smaller",onClick:M,ariaLabel:"Search in this chat"},c.a.createElement("i",{className:"icon-search"})),(h.f||!r)&&c.a.createElement(ne.a,{ref:j,className:g?"active":"",round:!0,ripple:!h.f,size:"smaller",color:"translucent",disabled:a,ariaLabel:"More actions",onClick:v},c.a.createElement("i",{className:"icon-more"})),p&&c.a.createElement(Ke,{chatId:e,threadId:t,isOpen:g,anchor:p,isChannel:s,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,onSubscribeChannel:w,onSearchClick:M,onClose:y,onCloseAnimationEnd:C}))})),Je=a(105),Ze=a(37),Xe=a(97),et=a(36);function tt(e){const t=e&&Object(m.E)(e),{sticker:a}=e&&e.content||{},s=t&&a&&!Object(h.o)()&&t.includes("image/webp"),[r,o]=Object(c.r)(et.a),i=e&&e.id;return Object(c.o)(()=>{s&&Object(et.c)("b64-"+i,t).then(o).catch(e=>{n.o&&console.error(e)})},[i,s,t]),s?r:t}var at=a(107),st=a(35),nt=a(28);function ct(e,t,a,s,n){return`M${e},${t+n}a${n},${n},0,0,1,\n ${a},0v${s-2*n}a${n},${n},0,0,1,${-a},0Z`}var rt=Object(c.h)(({count:e,index:t})=>{const a=Object(c.q)(null),s=Object(c.p)(()=>function(e,t){const a=e-t-1,s=function(e){let t=8;1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5);return t}(e),n=function(e,t){let a=36;1===e?a=36:2===e?a=17:3===e?a=1===t?12:11:(4===e||e>3)&&(a=7.5);return a}(e,a),c=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,s),r="clipPath"+e,o=function(e,t,a){let s="";if(3===a)s=ct(0,0,2,t,1)+ct(0,12,2,t+1,1)+ct(0,25,2,t,1);else for(let e=0;e\n \n `}(r,s,e),i=function(e,t,a){if(1===a)return 0;if(2===a)return 0===e?0:t+2;return 3===a?0===e?0:1===e?12:25:(t+2)*e}(a,s,e),l=function(e,t,a,s){if(t<=4)return 0;if(e<=1)return 0;if(e>=t-2)return s-36;return(a+4)/2+(e-2)*(a+2)}(a,e,s,c);return{markHeight:n,clipPath:o,markTranslateY:i,trackTranslateY:l,trackHeight:c,clipPathId:r}}(e,t),[e,t]);if(Object(c.n)(()=>{if(!a.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:n,markTranslateY:c,clipPathId:r,clipPath:o}=s,i=a.current.firstElementChild;if(a&&a.current){const s=a.current,{style:l}=s;l.height=e+"px",l.transform=`translateY(-${t}px)`,l.clipPath=`url("#${r}")`;const d=s.querySelector("svg"),b=s.querySelector("div"),u=s.querySelector("defs");d||i&&(i.innerHTML=` ${o} `),u&&(u.innerHTML=o),b&&(b.style.height=n+"px",b.style.transform=`translateY(${c}px)`)}},[s]),1===e)return c.a.createElement("div",{className:"pinned-message-border"},c.a.createElement("div",{className:"pinned-message-border-wrapper-1",ref:a}));const{trackHeight:n,trackTranslateY:r,markHeight:o,markTranslateY:i,clipPathId:l}=s;return c.a.createElement("div",{className:Object(K.a)("pinned-message-border",e>4&&"pinned-message-border-mask")},c.a.createElement("div",{className:"pinned-message-border-wrapper",ref:a,style:`clip-path: url("#${l}"); width: 2px;\n height: ${n}px; transform: translateY(-${r}px);`},c.a.createElement("span",null),c.a.createElement("div",{className:"pinned-message-border-mark",style:`height: ${o}px; transform: translateY(${i}px);`})))});var ot=Object(c.h)(({message:e,count:t,index:a,customTitle:s,className:n,onUnpinMessage:r,onClick:o,onAllPinnedClick:i})=>{const l=tt(e),d=Object(Xe.a)(Object(m.D)(e,"pictogram")),b=Object(m.M)(e,Boolean(l)),[u,h,O]=Object(nt.a)(),j=Object(c.m)(()=>{O(),r&&r(e.id)},[O,r,e.id]),g=Object(te.a)();return c.a.createElement("div",{className:Object(K.a)("HeaderPinnedMessage-wrapper",n)},t>1&&c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:g("EventLogFilterPinnedMessages"),onClick:i},c.a.createElement("i",{className:"icon-pin-list"})),r&&c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:g("UnpinMessageAlertTitle"),className:"unpin-button",onClick:h},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(at.a,{isOpen:u,onClose:O,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:j}),c.a.createElement("div",{className:"HeaderPinnedMessage",onClick:o},c.a.createElement(rt,{count:t,index:a}),l&&function(e,t){const{width:a,height:s}=Object(Je.k)();return c.a.createElement("img",{src:t||e,width:a,height:s,alt:""})}(l,d),c.a.createElement("div",{className:"message-text"},c.a.createElement("div",{className:"title"},s||`${g("PinnedMessage")} ${a>0?"#"+(t-a):""}`),c.a.createElement("p",null,Object(Ze.a)(b))),c.a.createElement(st.a,null)))}),it=a(48),lt=a(165);a(205);var dt=Object(s.h)((e,{message:t})=>{const a=Object(o.qb)(e,t);return{senderName:a?Object(m.U)(a):void 0}},(e,t)=>Object(d.l)(t,["focusMessage","closeAudioPlayer"]))(({message:e,className:t,noUi:a,senderName:s,focusMessage:n,closeAudioPlayer:r})=>{const o=it.c(Object(m.D)(e,"inline")),{playPause:i,isPlaying:l}=Object(lt.a)(Object(m.A)(e),Object(m.r)(e),o,void 0,void 0,!0),d=Object(c.m)(()=>{n({chatId:e.chatId,messageId:e.id})},[n,e.chatId,e.id]),b=Object(c.m)(()=>{l&&i(),r()},[r,l,i]),u=Object(te.a)();if(a)return;const O=Object(m.u)(e);return c.a.createElement("div",{className:Object(K.a)("AudioPlayer",t)},c.a.createElement(ne.a,{round:!0,ripple:!h.f,color:"translucent",size:"smaller",className:Object(K.a)("toggle-play",l?"pause":"play"),onClick:i,ariaLabel:l?"Pause audio":"Play audio"},c.a.createElement("i",{className:"icon-play"}),c.a.createElement("i",{className:"icon-pause"})),c.a.createElement("div",{className:"AudioPlayer-content",onClick:d},O?function(e){const{title:t,performer:a,fileName:s}=e;return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title"},Object(Ze.a)(t||s)),a&&c.a.createElement("div",{className:"subtitle"},Object(Ze.a)(a)))}(O):function(e,t){return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title"},t&&Object(Ze.a)(t)),c.a.createElement("div",{className:"subtitle"},e))}(u("AttachAudio"),s),c.a.createElement(st.a,null)),c.a.createElement(ne.a,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:b,ariaLabel:"Close player"},c.a.createElement("i",{className:"icon-close"})))});a(206);var bt=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const{isLeftColumnShown:n,lastSyncTime:c}=e,{byId:r}=e.chats,l=Object(o.f)(e,t),{typingStatus:d}=l||{},{chatId:b,messageId:u}=e.audioPlayer,h=b&&u?Object(o.k)(e,b,u):void 0,O=Object(o.Ab)(e,t,a);let j;if("pinned"===s){const a=Object(o.gb)(e,t);j=a&&a.length}else if("scheduled"===s){const a=Object(o.lb)(e,t);j=a&&a.length}else if("thread"===s&&a!==i.MAIN_THREAD_ID){const s=Object(o.zb)(e,t,a);s&&(j=s.messagesCount)}let g={typingStatus:d,isLeftColumnShown:n,isRightColumnShown:Object(o.V)(e),isSelectModeActive:Object(o.R)(e),audioMessage:h,chatTitleLength:l&&Object(m.l)(l).length,chatsById:r,originChatId:O?O.id:t,messagesCount:j,isChatWithSelf:Object(o.O)(e,t),isChatWithBot:l&&Object(o.N)(e,l),lastSyncTime:c};const f=Object(o.m)(e,t);if("thread"===s&&f)if(a===i.MAIN_THREAD_ID){const s=Object(o.gb)(e,t);if(s&&s.length){const t=f[s[0]],{canUnpin:n}=t&&Object(o.b)(e,t,a)||{};g={...g,pinnedMessageIds:s,messagesById:f,canUnpin:n}}}else{const s=Object(o.Bb)(e,t,a),n=s?Object(o.k)(e,t,s):void 0,c=n?Object(o.J)(e,n):void 0,r=c?Object(m.U)(c):void 0;g={...g,pinnedMessageIds:s,messagesById:f,canUnpin:!1,topMessageTitle:r}}return g},(e,t)=>Object(d.l)(t,["openChatWithInfo","pinMessage","focusMessage","openChat","loadPinnedMessages","toggleLeftColumn","exitMessageSelectMode"]))(({chatId:e,threadId:t,messageListType:a,pinnedMessageIds:s,messagesById:r,canUnpin:o,topMessageTitle:l,typingStatus:d,isSelectModeActive:b,isLeftColumnShown:u,isRightColumnShown:O,audioMessage:j,chatTitleLength:g,chatsById:f,originChatId:p,messagesCount:I,isChatWithSelf:v,isChatWithBot:y,lastSyncTime:C,openChatWithInfo:w,pinMessage:E,focusMessage:M,openChat:S,loadPinnedMessages:k,toggleLeftColumn:N,exitMessageSelectMode:P})=>{const[T,A]=Object(c.r)(0),x=Array.isArray(s)?s[T]:s,R=r&&x?r[x]:void 0,L=Array.isArray(s)?s.length:s?1:0;Object(c.n)(()=>{t===i.MAIN_THREAD_ID&&C&&k({chatId:e})},[e,k,C,t]),Object(c.n)(()=>{A(0)},[e]),Object(c.n)(()=>{A(L?Object(_e.a)(L,T):-1)},[L,T]),Object(ze.a)(e,x,R);const{width:F}=Ue(),D=F<=n.Y,B=F>=n.cb&&u,U=Object(c.q)(null),H=Object(c.q)(!0),q=Object(c.m)(()=>{w({id:e})},[w,e]),G=Object(c.m)(t=>{E({chatId:e,messageId:t,isUnpin:!0})},[E,e]),_=Object(c.m)(()=>{if(R){M({chatId:R.chatId,threadId:t,messageId:R.id});const e=Object(_e.a)(L,T+1);A(e)}},[R,M,t,L,T]),z=Object(c.m)(()=>{S({id:e,threadId:i.MAIN_THREAD_ID,type:"pinned"})},[S,e]),W=Object(c.m)(()=>{if(h.f){const e=document.getElementById(n.u);e&&e.blur()}t!==i.MAIN_THREAD_ID||"thread"!==a?("scheduled"===a&&b&&P(),S({id:p,threadId:i.MAIN_THREAD_ID})):h.f?S({id:void 0}):N()},[S,p,t,a,N,b,P]),V=Object(c.p)(()=>{if(!D||!f)return;let e=!1;const t=Object.values(f).reduce((t,a)=>{if(Object(m.gb)(a))return t;const s=a.unreadCount||0;return!s||a.isMuted&&!a.unreadMentionsCount||(e=!0),t+s},0);return t?{isActive:e,totalCount:t}:void 0},[D,f]),$=F>=n.Y&&Fn.cb&&F30),Q=$||F>n.Z&&F{const e=U.current;if(e)return Q&&oe?void(O||$?(H.current&&(e.classList.add("tools-stacked","animated"),H.current=!1),setTimeout(()=>{e.classList.remove("animated")},350)):(e.classList.remove("tools-stacked"),H.current=!0)):(e.classList.remove("tools-stacked","animated"),void(H.current=!0))},[Q,oe,$,O]);const ie=Object(te.a)();function le(){return"thread"===a&&t===i.MAIN_THREAD_ID?c.a.createElement(c.a.Fragment,null,D&&de(B,V),c.a.createElement("div",{className:"chat-info-wrapper",onClick:q},Object(m.kb)(e)?c.a.createElement($e.a,{userId:e,typingStatus:d,withFullInfo:y,withMediaViewer:!0,withUpdatingStatus:!0}):c.a.createElement(Qe.a,{chatId:e,typingStatus:d,withMediaViewer:!0,withFullInfo:!0,withUpdatingStatus:!0}))):"thread"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,ie("CommentsCount",I))):"pinned"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,ie("PinnedMessagesCount",I))):"scheduled"===a?c.a.createElement(c.a.Fragment,null,de(),c.a.createElement("h3",null,v?ie("Reminders"):ie("messages",I))):void 0}function de(e=!1,t){return c.a.createElement("div",{className:"back-button"},c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",onClick:W,ariaLabel:e?"Close":"Back"},c.a.createElement("div",{className:Object(K.a)("animated-close-icon",!e&&"state-back")})),t&&c.a.createElement("div",{className:"unread-count "+(t.isActive?"active":"")},Object(Ve.b)(t.totalCount)))}return c.a.createElement("div",{className:"MiddleHeader",ref:U},c.a.createElement(X.a,{name:"slide-fade",activeKey:"thread"===a?t:1},le),c.a.createElement("div",{className:"header-tools"},ae&&ce&&!J&&c.a.createElement(ot,{key:e,message:ce,count:L,index:T,customTitle:re,className:se,onUnpinMessage:o?G:void 0,onClick:_,onAllPinnedClick:z}),J&&ee&&c.a.createElement(dt,{key:Object(m.A)(ee),message:ee,className:Z}),c.a.createElement(Ye,{chatId:e,threadId:t,messageListType:a})))})),ut=a(151);function mt(e){return"albumId"in e}function ht(e,t){let a,s=[],n={originalDate:e[0].date,datetime:Number(Object(A.j)(1e3*e[0].date)),senderGroups:[s]};const c=[n];return e.forEach((r,o)=>{r.isInAlbum?a?(a.messages.push(r),r.content.text&&(a.mainMessage=r)):a={albumId:r.groupedId,messages:[r],mainMessage:r}:s.push(r);const i=e[o+1];if(!a||i&&i.groupedId&&i.groupedId===a.albumId||(s.push(a),a=void 0),i){const e=Number(Object(A.j)(1e3*i.date));n.datetime!==e?(n={originalDate:i.date,datetime:e,senderGroups:[]},c.push(n),s=[],n.senderGroups.push(s)):(i.id===t||r.senderId!==i.senderId||r.isOutgoing!==i.isOutgoing||Object(m.cb)(r)||Object(m.cb)(i)||r.forwardInfo&&i.forwardInfo&&(r.forwardInfo.senderUserId!==i.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==i.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==i.forwardInfo.hiddenUserName)||r.inlineButtons||i.inlineButtons)&&(s=[],n.senderGroups.push(s))}}),c}var Ot=a(96);function jt(){const[e,t]=Object(nt.a)(!1),a=(s=1e3,n=!1,Object(c.p)(()=>Object(g.a)(e=>e(),s,n,r),[s,n,r]));var s,n,r;return{isScrolled:e,updateStickyDates:Object(c.m)((e,s)=>{t(),document.body.classList.contains("is-scrolling-messages")||Object(g.b)(()=>{document.body.classList.add("is-scrolling-messages")}),a(()=>{Object(g.b)(()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const a=function(e,t){const a=e.querySelectorAll(".sticky-date"),s=e.scrollTop;return Array.from(a).find(e=>{const{offsetTop:a,offsetHeight:n}=e,c=a-s;return-n<=c&&c<=(t?60:10)})}(e,s);a&&a.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")})})},[t,a])}}var gt=a(146),ft=a(115);let pt=!1;var It=({containerRef:e,className:t,messageIds:a,containerHeight:s,listItemElementsRef:r,focusingId:o,anchorIdRef:i,anchorTopRef:l,loadMoreForwards:d,loadMoreBackwards:b,isViewportNewest:u,firstUnreadId:m,onFabToggle:h,children:O})=>{const j=Object(c.q)(null),g=Object(c.q)(null),f=Object(c.q)(null),p=Object(c.m)(()=>{if(pt)return;if(!a||!a.length)return void h(!1);if(!u)return void h(!0);const{offsetHeight:t,scrollHeight:s,scrollTop:n}=e.current,c=s-n-t;h(m?!(0===c):!(c<=50))},[a,u,e,h,m]),{observe:I,freeze:v,unfreeze:y}=Object(Ot.a)({rootRef:e,margin:n.T},t=>{if(!d||!b)return;const a=t.find(({isIntersecting:e})=>e);if(!a)return;const{target:s}=a;"backwards-trigger"===s.className?(Object(gt.a)(e.current),b()):"forwards-trigger"===s.className&&s.dataset.isActive&&(Object(gt.a)(e.current),d())});Object(Ot.c)(j,I),Object(Ot.c)(g,I);const{observe:C,freeze:w,unfreeze:E}=Object(Ot.a)({rootRef:e,margin:50},([{target:e}])=>{e.dataset.isActive&&p()});return Object(Ot.c)(f,C),Object(me.a)(()=>{o?(v(),w()):(E(),y())},[o]),Object(me.a)(()=>{if(!r.current)return;const e=r.current.filter(e=>a.includes(Number(e.dataset.messageId))),t=e[1]||e[0];t&&(i.current=t.id,l.current=t.getBoundingClientRect().top)},[a,s]),Object(me.a)(()=>{pt=!0,setTimeout(()=>{pt=!1},100)},[a]),Object(c.n)(p,[m]),c.a.createElement("div",{className:t,teactFastList:!0},c.a.createElement("div",{ref:j,key:"backwards-trigger",className:"backwards-trigger"}),O,c.a.createElement("div",{ref:g,key:"forwards-trigger",className:"forwards-trigger","data-is-active":!u}),c.a.createElement("div",{ref:f,key:"fab-trigger",className:"fab-trigger","data-is-active":u}))},vt=a(133),yt=a(135);function Ct(e){return"number"==typeof e}function wt(e){return e?175:100}function Et(e){const t=Object(m.sb)(e),a=Object(m.pb)(e),s=Object(m.G)(e)||Object(m.Q)(e),n=Object(m.O)(e),c=Boolean(Object(m.Q)(e)),{width:r,height:o}=s?Object(Je.f)(s,t,a,c):Object(Je.h)(n,t,a),i=wt(Boolean(Object(m.N)(e)));let l=1;re+t,t)}function At(e,t,a){return ea?a:e}function xt(e){const t={width:0,height:0};return e.forEach(({dimensions:e,sides:a})=>{a&kt&&(t.width=e.width+e.x),a&Nt&&(t.height=e.height+e.y)}),t}function Rt(e,t,a,s){const c=a.messages.map(e=>{const t=Et(e);return t.width/t.height});const r=function(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}(c),o=function(e){return e.reduce((e,t)=>t+e,1)/e.length}(c),i=c.length,l=c.some(e=>e>2),d=function(e,t,a){return a<=n.cb?a/100*69-(t?1.625:0)*Je.c:((e?30:29)-(t?1.625:0))*Je.c}(e,t,s);let b;const u={ratios:c,proportions:r,averageRatio:o,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return b=i>=5||l?function({ratios:e,averageRatio:t,maxWidth:a,minWidth:s,spacing:n,maxHeight:c=4*a/3}){const r=function(e,t){return e.map(e=>t>1.1?At(e,1,2.75):At(e,.6667,1))}(e,t),o=e.length,i=new Array(o),l=[],d=e=>{const t=[];let s=0;e.forEach(e=>{t.push(((e,t)=>{const s=Tt(r.slice(e,e+t),0);return(a-(t-1)*n)/s})(s,e)),s+=e}),l.push({lineCounts:e,heights:t})};for(let e=1;e!==o;++e){const t=o-e;e<=3&&t<=3&&d([e,t])}for(let e=1;e!==o-1;++e)for(let a=1;a!==o-e;++a){const s=o-e-a;e<=3&&a<=(t<.85?4:3)&&s<=3&&d([e,a,s])}for(let e=1;e!==o-1;++e)for(let t=1;t!==o-e;++t)for(let a=1;a!==o-e-t;++a){const s=o-e-t-a;e<=3&&t<=3&&a<=3&&s<=4&&d([e,t,a,s])}let b,u=0;for(let e=0;e{for(let e=1;e!==r;++e)if(a[e-1]>a[e])return 1.5;return 1})(),m=Math.abs(o-c)*i*d;(!b||m1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=Math.round(Math.min(a/t[0],Math.min(a/t[1],(n-s)/2)));return[{dimensions:{x:0,y:0,width:a,height:c},sides:Pt|St|kt},{dimensions:{x:0,y:c+s,width:a,height:c},sides:Pt|Nt|kt}]}(e):"ww"===a||"qq"===a?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=(a-s)/2,r=Math.round(Math.min(c/t[0],Math.min(c/t[1],n)));return[{dimensions:{x:0,y:0,width:c,height:r},sides:St|Pt|Nt},{dimensions:{x:c+s,y:0,width:c,height:r},sides:St|kt|Nt}]}(e):function(e){const{ratios:t,minWidth:a,maxWidth:s,spacing:n,maxHeight:c}=e,r=Math.round(1.5*a),o=Math.min(Math.round(Math.max(.4*(s-n),(s-n)/t[0]/(1/t[0]+1/t[1]))),s-n-r),i=s-o-n,l=Math.min(c,Math.round(Math.min(i/t[0],o/t[1])));return[{dimensions:{x:0,y:0,width:i,height:l},sides:St|Pt|Nt},{dimensions:{x:i+n,y:0,width:o,height:l},sides:St|kt|Nt}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:a,ratios:s,maxWidth:n,minWidth:c}=e,r=t,o=Math.round(Math.min((t-a)/2,s[1]*(n-a)/(s[2]+s[1]))),i=r-o-a,l=Math.max(c,Math.round(Math.min((n-a)/2,Math.min(o*s[2],i*s[1])))),d=Math.min(Math.round(r*s[0]),n-a-l);return[{dimensions:{x:0,y:0,width:d,height:r},sides:St|Pt|Nt},{dimensions:{x:d+a,y:0,width:l,height:i},sides:St|kt},{dimensions:{x:d+a,y:i+a,width:l,height:o},sides:Nt|kt}]}(e):function(e){const{maxWidth:t,ratios:a,maxHeight:s,spacing:n}=e,c=t,r=Math.round(Math.min(c/a[0],.66*(s-n))),o=(t-n)/2,i=Math.min(s-r-n,Math.round(Math.min(o/a[1],o/a[2])));return[{dimensions:{x:0,y:0,width:c,height:r},sides:Pt|St|kt},{dimensions:{x:0,y:r+n,width:o,height:i},sides:Nt|Pt},{dimensions:{x:o+n,y:r+n,width:c-o-n,height:i},sides:Nt|kt}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:a,maxHeight:s,minWidth:n}){const c=e,r=Math.round(Math.min(c/t[0],.66*(s-a))),o=Math.round((e-2*a)/(t[1]+t[2]+t[3])),i=Math.max(n,Math.round(Math.min(.4*(e-2*a),o*t[1]))),l=Math.round(Math.max(Math.max(n,.33*(e-2*a)),o*t[3])),d=c-i-l-2*a,b=Math.min(s-r-a,o);return[{dimensions:{x:0,y:0,width:c,height:r},sides:Pt|St|kt},{dimensions:{x:0,y:r+a,width:i,height:b},sides:Nt|Pt},{dimensions:{x:i+a,y:r+a,width:d,height:b},sides:Nt},{dimensions:{x:i+a+d+a,y:r+a,width:l,height:b},sides:kt|Nt}]}(e):function({maxHeight:e,ratios:t,maxWidth:a,spacing:s,minWidth:n}){const c=e,r=Math.round(Math.min(c*t[0],.6*(a-s))),o=Math.round((e-2*s)/(1/t[1]+1/t[2]+1/t[3])),i=Math.round(o/t[1]),l=Math.round(o/t[2]),d=c-i-l-2*s,b=Math.max(n,Math.min(a-r-s,o));return[{dimensions:{x:0,y:0,width:r,height:c},sides:St|Pt|Nt},{dimensions:{x:r+s,y:0,width:b,height:i},sides:St|kt},{dimensions:{x:r+s,y:i+s,width:b,height:l},sides:kt},{dimensions:{x:r+s,y:i+l+2*s,width:b,height:d},sides:Nt|kt}]}(e)}(u),{layout:b,containerStyle:xt(b)}}let Lt;function Ft(e){return Lt||(Lt=document.createElement("span"),Lt.style.font='400 12px Roboto, "Helvetica Neue", "Apple Color Emoji", sans-serif',Lt.style.whiteSpace="nowrap",Lt.style.position="absolute",Lt.style.left="-999px",Lt.style.opacity=".01",document.body.appendChild(Lt)),Lt.innerHTML=e,Lt.offsetWidth}function Dt(e,t,a,s,n){Object(c.o)(()=>{if(a&&e.current){const t=e.current.closest(".MessageList");Object(ft.a)(t,e.current,n?"end":"center",20,void 0===s?1500:1e3,s)}},[e,t,a,s,n])}var Bt=a(101),Ut=a(179);var Ht=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ContextMenuContainer",!t);return a?c.a.createElement(a,e):void 0};var qt=Object(c.h)(Object(s.h)((e,{message:t})=>{const a=t.senderId,{targetUserId:s,targetChatId:n}=t.content.action||{},c=t.replyToMessageId,r=c?Object(o.k)(e,t.chatId,c):void 0,i=Object(o.T)(e,t),{direction:l,noHighlight:d}=i&&e.focusedMessage||{},b=Object(o.f)(e,t.chatId);return{sender:b&&(Object(m.ib)(b)||a===t.chatId)?b:a?Object(o.Db)(e,a):void 0,...s&&{targetUser:Object(o.Db)(e,s)},targetChatId:n,targetMessage:r,isFocused:i,...i&&{focusDirection:l,noFocusHighlight:d}}})(({message:e,observeIntersection:t,isEmbedded:a,appearanceOrder:s=0,sender:n,targetUser:r,targetMessage:o,targetChatId:i,isFocused:l,focusDirection:d,noFocusHighlight:b})=>{const u=Object(c.q)(null);Object(Ot.c)(u,t),Object(ze.a)(e.chatId,e.replyToMessageId,o),Dt(u,e.chatId,l,d,b),Object(te.a)();const m=s<=0,[h,O]=Object(nt.a)(m);Object(c.n)(()=>{m||setTimeout(O,10*s)},[s,O,m]);const{transitionClassNames:j}=Object(Y.a)(h,void 0,m,!1),g=Object(Ut.a)(e,n,r,o,i,a?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:f,contextMenuPosition:p,handleBeforeContextMenu:I,handleContextMenu:v,handleContextMenuClose:y,handleContextMenuHide:C}=Object(vt.a)(u),w=void 0!==p;return a?c.a.createElement("span",{className:"embedded-action-message"},Object(Ze.a)(g)):c.a.createElement("div",{ref:u,id:"message"+e.id,className:Object(K.a)("ActionMessage message-list-item",l&&!b&&"focused",w&&"has-menu-open",j),"data-message-id":e.id,onMouseDown:I,onContextMenu:v},c.a.createElement("span",null,g),p&&c.a.createElement(Ht,{isOpen:f,anchor:p,message:e,messageListType:"thread",onClose:y,onCloseAnimationEnd:C}))}));a(207);var Gt=({className:e,message:t,sender:a,title:s,customText:n,observeIntersection:r,onClick:o})=>{const i=Object(c.q)(null),l=Object(Ot.b)(i,r),d=Object(Xe.a)(t&&Object(m.D)(t,"pictogram"),!l),b=t&&"sticker-reply-thumb"+t.id,u=tt(t);Object(te.a)();const h=a&&Object(m.U)(a);return c.a.createElement("div",{ref:i,className:Object(K.a)("EmbeddedMessage",e),onClick:t?o:void 0},u&&function(e,t,a){const{width:s,height:n}=Object(Je.k)();return c.a.createElement("img",{id:e,src:a||t,width:s,height:n,alt:""})}(b,u,d),c.a.createElement("div",{className:"message-text"},c.a.createElement("div",{className:"message-title"},Object(Ze.a)(h||s||" ")),c.a.createElement("p",null,t?Object(m.cb)(t)?c.a.createElement(qt,{message:t,isEmbedded:!0}):Object(Ze.a)(Object(m.M)(t,Boolean(u))):n||" ")))},_t=a(152),zt=a(157),Wt=a(162);a(211);var Vt=({message:e,outgoingStatus:t,signature:a,onClick:s})=>{const n=Object(te.a)();return c.a.createElement("span",{className:"MessageMeta",onClick:s},Boolean(e.views)&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"message-views"},Object(Ve.b)(e.views)),c.a.createElement("i",{className:"icon-channelviews"})),a&&c.a.createElement("span",{className:"message-signature"},Object(Ze.a)(a)),c.a.createElement("span",{className:"message-time"},e.isEdited&&n("EditedMessage")+" ",Object(A.h)(1e3*e.date)),t&&c.a.createElement(Wt.a,{status:t}))},$t=a(104),Qt=a(106),Kt=a(153);a(212);var Yt=({message:e,observeIntersection:t,observeIntersectionForPlaying:a,shouldLoop:s,lastSyncTime:r})=>{const o=Object(c.q)(null),[i,l,d]=Object(nt.a)(),b=e.content.sticker,{isAnimated:u,stickerSetId:h}=b,O=h===n.R,j=Object(Ot.b)(o,t),g=Object(Ot.b)(o,a),f=b.isPreloadedGlobally?"sticker"+b.id:Object(m.D)(e,"inline"),p=tt(e),I=Object(Xe.a)(f,!j,Object(m.C)(e,"inline",!0),r),v=Boolean(I),[y,C]=Object(nt.a)(v),w=u?y:v,{shouldRenderFullMedia:E,transitionClassNames:M}=Object($t.a)(w,"slow"),{width:S,height:k}=Object(Je.l)(b),N=Object(K.a)("thumbnail",!p&&"empty"),P=Object(K.a)("Sticker media-inner",O&&"inactive");return c.a.createElement("div",{ref:o,className:P,onClick:O?void 0:l},!w&&c.a.createElement("img",{id:"sticker-thumb-"+e.id,src:p,width:S,height:k,alt:"",className:N}),!u&&E&&c.a.createElement("img",{id:"sticker-"+e.id,src:I,width:S,height:k,alt:"",className:Object(K.a)("full-media",M)}),u&&v&&c.a.createElement(Qt.a,{key:f,className:Object(K.a)("full-media",M),id:f,animationData:I,size:S,play:g,noLoop:!s,onLoad:C}),c.a.createElement(Kt.a,{isOpen:i,fromSticker:b,onClose:d}))},Jt=a(119),Zt=a(111),Xt=a(136);function ea(e,t){return Object(Xt.a)(Object(m.E)(e),Boolean(t),h.f?n.H:void 0)}var ta=async(e,t,a,s)=>s?"rgba(255,255,255,1)":async function(e,t){const a=new Image;a.src=e,a.width||await new Promise(e=>{a.onload=e});const s=document.createElement("canvas"),n=s.getContext("2d");s.width=a.width,s.height=a.height,n.drawImage(a,0,0,a.width,a.height);const c=t?a.width-1:0,r=a.height-1;return`rgba(${Array.from(n.getImageData(c,r,1,1).data).join(",")})`}(e,t);var aa=a(112);var sa=({id:e,message:t,observeIntersection:a,shouldAutoLoad:s,isInSelectMode:n,isSelected:r,uploadProgress:o,size:i="inline",dimensions:l,shouldAffectAppendix:d,onClick:b,onCancelUpload:u})=>{const h=Object(c.q)(null),O=(Object(m.G)(t)||Object(m.Q)(t)).blobUrl,j=Object(Ot.b)(h,a),[g,f]=Object(c.r)(s),p=g&&j,{mediaData:I,downloadProgress:v}=Object(Zt.a)(Object(m.D)(t,i),!p),y=O||I,C=ea(t,y),{isUploading:w,isTransferring:E,transferProgress:M}=Object(m.s)(t,o||v,p&&!y),S=!1===Object(He.a)(g),{shouldRender:k,transitionClassNames:N}=Object(Y.a)(E,void 0,S,"slow"),{shouldRenderThumb:P,shouldRenderFullMedia:T,transitionClassNames:A}=Object($t.a)(y,"slow"),x=Object(c.m)(()=>{w?u&&u(t):y?b&&b(t.id):f(e=>!e)},[y,w,t,u,b]),R=Object(m.sb)(t);Object(c.o)(()=>{if(!d)return;const e=h.current.closest(".message-content");y?ta(y,R,0,r).then(t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")}):e.classList.add("has-appendix-thumb")},[y,R,d,n,r]);const{width:L,height:F,isSmall:D}=l||Et(t),B=Object(K.a)("media-inner",!w&&"interactive",D&&"small-image",L===F&&"square-image"),U=Object(K.a)("thumbnail",!C&&"empty"),H=l?`width: ${L}px; height: ${F}px; left: ${l.x}px; top: ${l.y}px;`:"";return c.a.createElement("div",{id:e,ref:h,className:B,style:H,onClick:w?void 0:x},P&&c.a.createElement("img",{src:C,className:U,width:L,height:F,alt:""}),T&&c.a.createElement("img",{src:y,className:"full-media "+A,width:L,height:F,alt:""}),k&&c.a.createElement("div",{className:"media-loading "+N},c.a.createElement(aa.a,{progress:M,onClick:w?x:void 0})),!y&&!g&&c.a.createElement("i",{className:"icon-download"}),E&&c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*M),"%"))},na=a(125),ca=a(124);function ra(e,t){const a=Object(c.q)();a.current=t;const s=Object(c.m)(()=>{e.current&&e.current.pause()},[e]),n=Object(c.m)(()=>{e.current&&a.current&&Object(ca.a)(e.current)},[e]);Object(Q.a)(s,n)}var oa=a(137),ia=(e,t=!1)=>{const a=Object(c.q)(!1),s=Object(c.q)(!1),n=Object(c.m)(()=>{s.current=!0,t&&e.current&&(a.current||(a.current=!e.current.paused),e.current.pause())},[t,e]),r=Object(c.m)(()=>{t&&e.current&&a.current&&document.body.contains(e.current)&&Object(ca.a)(e.current),a.current=!1,s.current=!1},[t,e]),o=Object(c.m)(()=>{Object(g.b)(r)},[r]);document.hasFocus()||n(),Object(J.a)(n,o)};function la(){return(la=Object.assign||function(e){for(var t=1;t{const b=Object(c.q)(null),u=Object(c.q)(null),h=t.content.video,O=h.blobUrl,j=Boolean(O)||Object(m.b)(h),g=Object(Ot.b)(b,a),[f,p]=Object(c.r)(s),I=Boolean(f&&g&&o),[v,y]=Object(c.r)(n),C=Object(Xe.a)(Object(m.D)(t,"pictogram"),!(g&&o),Object(m.C)(t,"pictogram"),o),w=ea(t,C),{mediaData:E,downloadProgress:M}=Object(Zt.a)(Object(m.D)(t,"inline"),!I,Object(m.C)(t,"inline"),o),S=C||w,k=O||E,N=Boolean(j&&g&&k),{isBuffered:P,bufferingHandlers:T}=Object(na.a)(!s),{isUploading:x,isTransferring:R,transferProgress:L}=Object(m.s)(t,r||M,I&&j&&!P),F=!1===Object(He.a)(f),{shouldRender:D,transitionClassNames:B}=Object(Y.a)(R,void 0,F),{shouldRenderThumb:U,transitionClassNames:H}=Object($t.a)(k,"slow"),[q,G]=Object(c.r)(0),_=Object(c.m)(e=>{G(Math.max(0,e.currentTarget.currentTime-1))},[]),z=Object(m.sb)(t),W=Object(m.pb)(t),{width:V,height:$}=i||Object(Je.h)(h,z,W);ra(u,Boolean(N&&n)),ia(u,v),Object(oa.a)(u,[N]);const Q=Object(c.m)(()=>{x?d&&d(t):j&&!k?p(e=>!e):j&&k&&!v?(y(!0),u.current.play()):l&&l(t.id)},[x,j,k,v,l,d,t]),J=Object(K.a)("media-inner dark",!x&&"interactive"),Z=Object(K.a)("thumbnail",!S&&"empty"),X=Object(K.a)("full-media",H),ee=S?`background-image: url(${S}); background-size: cover`:"",te=i?`width: ${V}px; height: ${$}px; left: ${i.x}px; top: ${i.y}px;`:"",ae=N,se=!j&&E,ne=!j||f&&!v&&!D,ce=j&&!f;return c.a.createElement("div",{ref:b,id:e,className:J,style:te,onClick:x?void 0:Q},(U||!N)&&c.a.createElement("img",{src:S,className:Z,width:V,height:$,alt:""}),ae&&c.a.createElement("video",la({ref:u,className:X,width:V,height:$,autoPlay:v,muted:!0,loop:!0,playsInline:!0,style:ee},T,{onTimeUpdate:_}),c.a.createElement("source",{src:k})),se&&c.a.createElement("img",{src:E,className:"full-media "+H,width:V,height:$,alt:""}),ne&&c.a.createElement("i",{className:"icon-large-play"}),D&&c.a.createElement("div",{className:"media-loading "+B},c.a.createElement(aa.a,{progress:L,onClick:x?Q:void 0})),ce&&c.a.createElement("i",{className:"icon-download"}),R&&!j?c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*L),"%"):R&&j?c.a.createElement("span",{className:"message-upload-progress"},"..."):c.a.createElement("div",{className:"message-media-duration"},h.isGif?"GIF":Object(A.e)(h.duration-q)))},ba=a(18);a(214);var ua=Object(s.h)((e,{contact:t})=>({user:Object(o.Db)(e,t.userId)}),(e,t)=>Object(d.l)(t,["openUserInfo"]))(({contact:e,user:t,openUserInfo:a})=>{const{firstName:s,lastName:n,phoneNumber:r,userId:o}=e,i=Object(c.m)(()=>{a({id:o})},[a,o]);return c.a.createElement("div",{className:Object(K.a)("Contact",Boolean(o)&&"interactive"),onClick:o?i:void 0},c.a.createElement(Bt.a,{size:"large",user:t,text:s||n}),c.a.createElement("div",{className:"contact-info"},c.a.createElement("div",{className:"contact-name"},s," ",n),c.a.createElement("div",{className:"contact-phone"},Object(ba.c)(r))))}),ma=a(41);var ha=Object(c.h)(({id:e,options:t,selected:a=[],disabled:s,round:n,loadingOptions:r,onChange:o})=>{const[i,l]=Object(c.r)([]),d=Object(c.m)(e=>{const{value:t,checked:a}=e.currentTarget;let s;s=a?[...i,t]:i.filter(e=>e!==t),l(s),o(s)},[o,i]);return c.a.createElement("div",{id:e,className:"radio-group"},t.map(e=>c.a.createElement(ma.a,{label:e.label,subLabel:e.subLabel,value:e.value,checked:-1!==a.indexOf(e.value),disabled:s,round:n,isLoading:r?-1!==r.indexOf(e.value):void 0,onChange:d})))}),Oa=a(117),ja=a(170);a(217);function ga(e,t){return t>0?(e/t*100).toFixed():0}var fa=({answer:e,voteResults:t,totalVoters:a,maxVotersCount:s,correctResults:n,shouldAnimate:r})=>{const o=t&&t.find(t=>t.option===e.option),i=0===n.length||-1!==n.indexOf(e.option),l=n.length>0&&i||o&&o.isChosen,d=o?ga(o.votersCount,a||0):0,[b,u]=Object(c.r)(r?0:d),m=Object(c.q)(null),h=o?ga(o.votersCount,s||0):0,O=b{r&&u(d)},[r,d]),Object(c.n)(()=>{const e=m.current;if(e&&r){const t=e.firstElementChild,a=O?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",a):e.innerHTML=`\n \n \n `}},[O,r]),!t||!o)return;const j=`width: ${h}%; transform:scaleX(${O?0:1})`;return c.a.createElement("div",{className:"PollOption"},c.a.createElement("div",{className:"poll-option-share "+("100"===d?"limit-width":"")},d,"%",l&&c.a.createElement("span",{className:Object(K.a)("poll-option-chosen",!i&&"wrong",r&&"animate")},c.a.createElement("i",{className:i?"icon-check":"icon-close"}))),c.a.createElement("div",{className:"poll-option-right"},c.a.createElement("div",{className:"poll-option-text"},Object(Ze.a)(e.text)),c.a.createElement("div",{className:Object(K.a)("poll-option-answer",l&&!i&&"wrong")},c.a.createElement("div",{className:"poll-option-corner",ref:m}),c.a.createElement("div",{className:"poll-option-line",style:j}))))};a(218);var pa=Object(c.h)(Object(s.h)((e,{poll:t})=>{const{recentVoterIds:a}=t.results,{byId:s}=e.users;return a&&0!==a.length?{recentVoterIds:a,usersById:s}:{}},(e,t)=>Object(d.l)(t,["loadMessage","openPollResults"]))(({message:e,poll:t,recentVoterIds:a,usersById:s,loadMessage:n,onSendVote:r,openPollResults:o})=>{const{id:i,chatId:l}=e,{summary:d,results:b}=t,[u,m]=Object(c.r)(!1),[h,O]=Object(c.r)([]),[j,g]=Object(c.r)(!1),[f,p]=Object(c.r)(!1),[I,v]=Object(c.r)(!d.closed&&d.closeDate&&d.closeDate>0?Math.min(d.closeDate-Math.floor(Date.now()/1e3),d.closePeriod):0),y=Object(c.q)(null),{results:C,totalVoters:w}=b,E=C&&C.some(e=>e.isChosen),M=!d.closed&&!E,S=!M&&d.isPublic&&Number(b.totalVoters)>0,k=M&&d.multipleChoice,N=C?Math.max(...C.map(e=>e.votersCount)):w,P=C?C.reduce((e,t)=>(t.isCorrect&&e.push(t.option),e),[]):[],T=d.answers.map(e=>({label:e.text,value:e.option,hidden:Boolean(d.quiz&&d.closePeriod&&I<=0)}));Object(c.n)(()=>{u&&t.results.results&&t.results.results.some(e=>e.isChosen)&&m(!1)},[u,t.results.results]),Object(c.n)(()=>{I>0&&setTimeout(()=>v(I-1),1e3);const e=y.current;if(e){const t=12*Math.PI,a=e.lastElementChild,s=e.firstElementChild;if(I<=5&&e.classList.add("hurry-up"),a&&s){const e=(d.closePeriod-I)/d.closePeriod*t;s.textContent=Object(A.e)(I),a.firstElementChild.setAttribute("stroke-dashoffset","-"+e)}else e.innerHTML=`\n ${Object(A.e)(I)}\n \n \n `}},[I,d.closePeriod]),Object(c.n)(()=>{d.quiz&&(I<=0||E&&!d.closed)&&n({chatId:l,messageId:i})},[l,I,E,n,i,d.closed,d.quiz]),Object(c.n)(()=>{let e;return d.quiz&&!d.closed&&d.closePeriod&&d.closePeriod>0&&(e=window.setTimeout(()=>{n({chatId:l,messageId:i})},1e3*d.closePeriod)),()=>{e&&window.clearTimeout(e)}},[M,l,n,i,d.closePeriod,d.closed,d.quiz]);const x=Object(c.p)(()=>a?a.reduce((e,t)=>{const a=s[t];return a&&e.push(a),e},[]):[],[s,a]),R=Object(c.m)(e=>{O([e]),m(!0),p(!0),r([e])},[r]),L=Object(c.m)(e=>{O(e)},[]),F=Object(c.m)(()=>{m(!0),p(!0),r(h)},[r,h]),D=Object(c.m)(()=>{o({chatId:l,messageId:i})},[l,i,o]),B=Object(c.m)(()=>{g(!0)},[]),U=Object(c.m)(()=>{g(!1),p(!1)},[]);Object(c.n)(()=>{if(f&&E&&d.quiz&&b.results&&t.results.solution){b.results.find(e=>e.isChosen&&e.isCorrect)||g(!0)}},[E,f,b.results,d.quiz,t.results.solution]);const H=Object(te.a)();return c.a.createElement("div",{className:"Poll"},j&&t.results.solution&&c.a.createElement(ja.a,{message:Object(yt.b)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:U}),c.a.createElement("div",{className:"poll-question"},Object(Ze.a)(d.question)),c.a.createElement("div",{className:"poll-type"},function(e){if(void 0===e.isPublic)return" ";if(e.quiz)return e.isPublic?"Quiz":"Anonymous Quiz";if(e.closed)return"Final results";return e.isPublic?"Poll":"Anonymous Poll"}(d),x.length>0&&c.a.createElement("div",{className:"poll-recent-voters"},x.map(e=>c.a.createElement(Bt.a,{size:"micro",user:e}))),I>0&&M&&c.a.createElement("div",{ref:y,className:"poll-countdown"}),d.quiz&&t.results.solution&&!M&&c.a.createElement(ne.a,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:j,onClick:B,ariaLabel:"Show Solution"},c.a.createElement("i",{className:"icon-lamp"}))),M&&c.a.createElement("div",{className:"poll-answers"},k?c.a.createElement(ha,{options:T,onChange:L,disabled:e.isScheduled||u,loadingOptions:u?h:void 0,round:!0}):c.a.createElement(Oa.a,{name:"poll-"+i,options:T,onChange:R,disabled:e.isScheduled||u,loadingOption:u?h[0]:void 0})),!M&&c.a.createElement("div",{className:"poll-results"},d.answers.map((function(e){return c.a.createElement(fa,{key:e.option,shouldAnimate:f,answer:e,voteResults:C,totalVoters:w,maxVotersCount:N,correctResults:P})}))),!S&&!k&&c.a.createElement("div",{className:"poll-voters-count"},function(e,t){if(!t)return e?"No answers yet":"No voters yet";return e?t+" answered":t+" voted"}(d.quiz,b.totalVoters)),k&&c.a.createElement(ne.a,{isText:!0,disabled:0===h.length,size:"tiny",onClick:F},H("PollSubmitVotes")),S&&c.a.createElement(ne.a,{isText:!0,size:"tiny",onClick:D},H("PollViewResults")))})),Ia=a(147),va=a(51);a(219);var ya=Object(c.h)(({message:e,observeIntersection:t,shouldAutoLoad:a,inPreview:s,onMediaClick:n,onCancelMediaTransfer:r})=>{const o=Object(m.P)(e);let i=!1;if(o&&o.photo){const{width:t,height:a}=Et(e);i=t===a}const l=Object(c.m)(()=>{o&&(i||o.hasDocument)?window.open(o.url):n&&n()},[o,i,n]);if(!o)return;const{siteName:d,url:b,displayUrl:u,title:h,description:O,photo:j}=o,g=Object(Ia.a)(O,170),f=Object(K.a)("WebPage",j?i&&"with-square-photo":!s&&"without-photo");return c.a.createElement("div",{className:f,"data-initial":(d||u)[0]},j&&c.a.createElement(sa,{message:e,observeIntersection:t,shouldAutoLoad:a,size:i?"pictogram":"inline",onClick:l,onCancelUpload:r}),c.a.createElement("div",{className:"WebPage-text"},c.a.createElement(va.a,{className:"site-name",url:b,text:d||u}),!s&&h&&c.a.createElement("p",{className:"site-title"},Object(Ze.a)(h)),g&&c.a.createElement("p",{className:"site-description"},Object(Ze.a)(g,["emoji","br"]))))});a(220);var Ca=Object(c.h)(({message:e})=>{const t=Object(m.z)(e),{title:a,text:s,description:n,photoUrl:r}=t;return c.a.createElement("div",{className:"Invoice"},a&&c.a.createElement("p",{className:"title"},Object(Ze.a)(a)),s&&c.a.createElement("p",null,Object(Ze.a)(s,["emoji","br"])),c.a.createElement("div",{className:"description "+(r?"has-image":"")},r&&c.a.createElement("img",{className:"invoice-image",src:r,alt:""}),n&&c.a.createElement("p",{className:"description-text"},Object(Ze.a)(n,["emoji","br"]))))});function wa(e){return Object(c.h)(Object(s.h)((e,t)=>{const{message:a}=t;return{isInSelectMode:Object(o.R)(e),isSelected:Object(o.U)(e,a.id)}},(e,t)=>Object(d.l)(t,["toggleMessageSelection"]))(t=>{const{isInSelectMode:a,isSelected:s,message:n,toggleMessageSelection:r,dimensions:o}=t,i=Object(c.m)(e=>{e.stopPropagation(),r({messageId:n.id,withShift:e&&e.shiftKey})},[r,n]),l=Object(c.p)(()=>({...t,isInSelectMode:a,isSelected:s,dimensions:{...t.dimensions,x:0,y:0},onClick:a?void 0:t.onClick}),[t,a,s]);return c.a.createElement("div",{className:Object(K.a)("album-item-select-wrapper",s&&"is-selected"),style:o?`left: ${o.x}px; top: ${o.y}px;`:"",onClick:a?i:void 0},a&&c.a.createElement("div",{className:"message-select-control"},s&&c.a.createElement("i",{className:"icon-select"})),c.a.createElement(e,l))}))}a(221);const Ea=wa(sa),Ma=wa(da);var Sa=Object(s.h)(e=>({uploadsById:e.fileUploads.byMessageLocalId}),(e,t)=>Object(d.l)(t,["cancelSendingMessage"]))(({album:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,hasCustomAppendix:n,lastSyncTime:r,isOwn:o,albumLayout:i,onMediaClick:l,uploadsById:d,cancelSendingMessage:b})=>{const u=e.messages.length,h=Object(c.m)(e=>{b({chatId:e.chatId,messageId:e.id})},[b]);const{width:O,height:j}=i.containerStyle;return c.a.createElement("div",{className:"Album",style:`width: ${O}px; height: ${j}px;`},e.messages.map((function(e,b){const{photo:O,video:j}=Object(m.v)(e),g=d[e.previousLocalId||e.id],f=g?g.progress:void 0,{dimensions:p,sides:I}=i.layout[b];if(O){const s=n&&(o?b===u-1:Boolean(I&Pt&&I&Nt));return c.a.createElement(Ea,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAffectAppendix:s,uploadProgress:f,dimensions:p,onClick:l,onCancelUpload:h})}if(j)return c.a.createElement(Ma,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,uploadProgress:f,lastSyncTime:r,dimensions:p,onClick:l,onCancelUpload:h})})))});a(222);function ka(){return(ka=Object.assign||function(e){for(var t=1;t{const r=Object(c.q)(null),o=Object(c.q)(null),i=Object(c.q)(null),l=e.content.video,d=Object(Ot.b)(r,t),[b,u]=Object(c.r)(a&&s),h=Boolean(b&&d&&n),{mediaData:O,downloadProgress:j}=Object(Zt.a)(Object(m.D)(e,"inline"),!h,Object(m.C)(e,"inline"),n),g=ea(e,O),{isBuffered:f,bufferingHandlers:p}=Object(na.a)(),I=b&&!f,v=!1===Object(He.a)(b),{shouldRender:y,transitionClassNames:C}=Object(Y.a)(I||!f,void 0,v),{shouldRenderThumb:w,transitionClassNames:E}=Object($t.a)(O,"slow"),[M,S]=Object(c.r)(!1),[k,N]=Object(c.r)(0);Object(c.n)(()=>{if(!M)return;const e=188*Math.PI,t=e-k*e,a=i.current,s=o.current,n=s.firstElementChild;n?n.firstElementChild.setAttribute("stroke-dashoffset",t.toString()):s.innerHTML=`\n \n `,N(a.currentTime/a.duration)},[M,k]);const P=Boolean(O&&d),T=()=>{S(!1),N(0),Object(ca.a)(i.current),requestAnimationFrame(()=>{o.current.innerHTML=""})},x=(R=T,()=>{Na&&Na(),Na=R});var R;Object(c.n)(()=>{i.current&&(P?Object(ca.a)(i.current):i.current.pause())},[P]),ra(i,P),ia(i,Boolean(O)),Object(oa.a)(i,[O]);const L=Object(c.m)(()=>{if(!O)return void u(e=>!e);const e=i.current;M?e.paused?Object(ca.a)(e):e.pause():(e.currentTime=0,S(!0),x())},[x,M,O]),F=Object(c.m)(e=>{const t=e.currentTarget;N(t.currentTime/t.duration)},[]),D=Object(K.a)("full-media",E);return c.a.createElement("div",{ref:r,className:"RoundVideo media-inner",onClick:L},w&&c.a.createElement("div",{className:"thumbnail-wrapper"},c.a.createElement("img",{src:g,className:"thumbnail",width:Je.d,height:Je.d,alt:""})),O&&c.a.createElement("div",{className:"video-wrapper"},c.a.createElement("video",ka({ref:i,className:D,width:Je.d,height:Je.d,autoPlay:!0,muted:!M,loop:!M,playsInline:!0,poster:g,onEnded:M?T:void 0},p,{onTimeUpdate:M?F:void 0}),c.a.createElement("source",{src:O}))),c.a.createElement("div",{className:"progress",ref:o}),y&&c.a.createElement("div",{className:"media-loading "+C},c.a.createElement(aa.a,{progress:j})),!O&&!b&&c.a.createElement("i",{className:"icon-large-play"}),c.a.createElement("div",{className:"message-media-duration"},M?Object(A.e)(i.current.currentTime):Object(A.e)(l.duration),(!M||i.current.paused)&&c.a.createElement("i",{className:"icon-muted-chat"})))};a(223);var Ta=({message:e,onClick:t})=>c.a.createElement("div",{className:"InlineButtons"},e.inlineButtons.map(e=>c.a.createElement("div",{className:"row"},e.map(e=>c.a.createElement(ne.a,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},e.text)))));a(224);var Aa=Object(c.h)(Object(s.h)((e,{message:t})=>{const{threadId:a,chatId:s}=t.threadInfo,n=Object(o.zb)(e,s,a)||t.threadInfo,{byId:c}=e.users,{byId:r}=e.chats;return{threadInfo:n,usersById:c,chatsById:r}},(e,t)=>Object(d.l)(t,["openChat"]))(({disabled:e,threadInfo:t,usersById:a,chatsById:s,openChat:n})=>{const{threadId:r,chatId:o,messagesCount:i,lastMessageId:l,lastReadInboxMessageId:d,recentReplierIds:b}=t,u=Object(c.m)(()=>{n({id:o,threadId:r})},[n,o,r]);if(void 0===i)return;const h=b&&b.map(e=>Object(m.kb)(e)?a[e]:s[e]).filter(Boolean);const O=Boolean(d&&l&&d0&&c.a.createElement("div",{className:"recent-repliers"},h.map(e=>c.a.createElement(Bt.a,{key:e.id,size:"small",user:Object(m.kb)(e.id)?e:void 0,chat:Object(m.kb)(e.id)?void 0:e}))),c.a.createElement("div",{className:"label"},function(e){if(0===e)return"Leave a Comment";if(1===e)return"1 Comment";return Object(Ve.a)(e)+" Comments"}(i)),c.a.createElement("i",{className:"icon-next"}))}));a(225);function xa(e){const t=La(e.currentTarget);t&&t.setAttribute("data-is-document-group-hover","")}function Ra(e){const t=La(e.currentTarget);t&&t.removeAttribute("data-is-document-group-hover")}function La(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}var Fa=Object(c.h)(Object(s.h)((e,t)=>{const{focusedMessage:a,forwardMessages:s,lastSyncTime:n}=e,{message:c,album:r,withSenderName:i,withAvatar:l,threadId:d,messageListType:b}=t,{id:u,chatId:h,viaBotId:O,replyToMessageId:j,isOutgoing:g}=c,f=Object(o.f)(e,h),p=Object(o.O)(e,h),I=f&&Object(m.ib)(f),v=!p&&Object(m.db)(c),y=i||l||v?Object(o.qb)(e,c):void 0,C=Object(o.J)(e,c),w=O?Object(o.Db)(e,O):void 0,E=d?Object(o.Bb)(e,h,d):void 0,M=c.id===E,S=j===E,k=j&&!S?Object(o.k)(e,h,j):void 0,N=k&&Object(o.qb)(e,k),P=Object(o.Cb)(e,c),T="thread"===b&&(r?r.messages.some(t=>Object(o.T)(e,t)):Object(o.T)(e,c)),{direction:A,noHighlight:x}=T&&a||{},R=s.messageIds&&s.messageIds.includes(u),{query:L}=Object(o.A)(e)||{},F=Object(m.K)(c);let D;return D=r&&r.messages?r.messages.every(({id:t})=>Object(o.U)(e,t)):Object(o.U)(e,u),{forceSenderName:v,sender:y,originSender:C,botSender:w,shouldHideReply:S,isThreadTop:M,replyMessage:k,replyMessageSender:N,...g&&{outgoingStatus:Object(o.cb)(e,c,"scheduled"===b)},..."number"==typeof P&&{uploadProgress:P},isFocused:T,...T&&{focusDirection:A,noFocusHighlight:x},isForwarding:R,isChatWithSelf:p,isChannel:I,lastSyncTime:n,highlight:L,isSingleEmoji:Boolean(F),animatedEmoji:F?Object(o.c)(e,F):void 0,isInSelectMode:Object(o.R)(e),isSelected:D,isGroupSelected:!!c.groupedId&&!c.isInAlbum&&Object(o.P)(e,h,c.groupedId),threadId:d,isPinnedList:"pinned"===b,shouldAutoLoadMedia:f?Object(o.rb)(e,c,f,y):void 0,shouldAutoPlayMedia:Object(o.sb)(e,c),shouldLoopStickers:Object(o.tb)(e)}},(e,t)=>Object(d.l)(t,["focusMessage","openMediaViewer","openAudioPlayer","cancelSendingMessage","openUserInfo","openChat","markMessagesRead","sendPollVote","toggleMessageSelection","setReplyingToId","openForwardMenu","clickInlineButton"]))(({message:e,observeIntersectionForBottom:t,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:s,album:n,withAvatar:r,withSenderName:o,noComments:d,appearanceOrder:b,isFirstInGroup:u,isLastInGroup:h,isFirstInDocumentGroup:O,isLastInDocumentGroup:j,isLastInList:g,forceSenderName:f,sender:p,originSender:I,botSender:v,isThreadTop:y,shouldHideReply:C,replyMessage:w,replyMessageSender:E,outgoingStatus:M,uploadProgress:S,isFocused:k,focusDirection:N,noFocusHighlight:P,isForwarding:T,isChatWithSelf:A,isChannel:x,lastSyncTime:R,highlight:L,animatedEmoji:F,isInSelectMode:D,isSelected:B,isGroupSelected:U,threadId:H,messageListType:q,isPinnedList:G,shouldAutoLoadMedia:_,shouldAutoPlayMedia:z,shouldLoopStickers:W,focusMessage:V,openMediaViewer:$,openAudioPlayer:Q,openUserInfo:J,openChat:Z,cancelSendingMessage:X,markMessagesRead:ee,sendPollVote:ae,toggleMessageSelection:se,setReplyingToId:ce,openForwardMenu:re,clickInlineButton:oe})=>{const ie=Object(c.q)(null),le=Object(c.q)(null),de=Object(c.q)(null);Object(Ot.c)(le,t);const{width:be}=Ue(),{isContextMenuOpen:ue,contextMenuPosition:me,handleBeforeContextMenu:he,handleContextMenu:Oe,handleContextMenuClose:je,handleContextMenuHide:ge}=Object(vt.a)(ie),fe=b<=0,[pe,Ie]=Object(nt.a)(fe);Object(c.n)(()=>{fe||setTimeout(Ie,10*b)},[b,Ie,fe]);const{transitionClassNames:ve}=Object(Y.a)(pe,void 0,fe,!1),{chatId:ye,id:Ce,threadInfo:we}=e,Ee=Object(m.sb)(e),Me="scheduled"===q||e.isScheduled,Se=Object(m.tb)(e)&&!C,ke=Boolean(we)&&"thread"===q,{forwardInfo:Ne,viaBotId:Pe}=e,Te=Ne&&!A&&!Ne.isLinkedChannelPost,Ae=!!e.groupedId&&!e.isInAlbum,xe=Boolean(n)&&n.messages.length>1,{text:Re,photo:Le,video:Fe,audio:De,voice:Be,document:He,sticker:qe,contact:Ge,poll:_e,webPage:We,invoice:Ve}=Object(m.v)(e),$e=Object(m.x)(e),Qe=Object(yt.a)(e,L,Ct($e)),Ke=void 0!==me,Ye=Object(K.a)("Message message-list-item",u&&"first-in-group",h&&"last-in-group",O&&"first-in-document-group",j&&"last-in-document-group",g&&"last-in-list",Ee&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Se&&"has-reply",Ke&&"has-menu-open",k&&!P&&"focused",T&&"is-forwarding",e.isDeleting&&"is-deleting",Ae&&"is-in-document-group",xe&&"is-album",e.hasUnreadMention&&"has-unread-mention",B&&"is-selected",D&&"is-in-selection-mode",y&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",ve),Xe=function(e,{hasReply:t,customShape:a,isLastInGroup:s,asForwarded:n,hasThread:c,forceSenderName:r,hasComments:o}={}){const{text:i,photo:l,video:d,audio:b,voice:u,document:h,poll:O,webPage:j,contact:g}=Object(m.v)(e),f=["message-content"],p=(l||d)&&!i,I=Boolean(e.viaBotId);return Ct(a)?f.push("emoji-only emoji-only-"+a):i&&f.push("text"),a&&(f.push("custom-shape"),d&&d.isRound&&f.push("round"),o&&f.push("has-comments")),l||d?f.push("media"):b?f.push("audio"):u?f.push("voice"):h?f.push("document"):g?f.push("contact"):O?f.push("poll"):j&&(f.push("web-page"),j.photo&&f.push("media")),n&&!a&&f.push("is-forwarded"),t&&f.push("is-reply"),c&&f.push("has-replies"),I&&f.push("is-via-bot"),r&&f.push("force-sender-name"),a||(f.push("has-shadow"),(t||n||!p||I||r)&&f.push("has-solid-background"),!s||!l&&p||f.push("has-appendix")),f.join(" ")}(e,{hasReply:Se,customShape:$e,isLastInGroup:h,asForwarded:Te,hasThread:ke,forceSenderName:f,hasComments:e.threadInfo&&e.threadInfo.messagesCount>0}),et=!Ne||!A&&p?p:I,tt=Ne?I:p,at=x&&e.adminTitle||Ne&&!Te&&Ne.adminTitle||void 0;Object(ze.a)(ye,Se?e.replyToMessageId:void 0,w,e.id),Dt(ie,ye,k,N,P),Object(c.o)(()=>{de.current&&(de.current.innerHTML=Ee?'':'')},[Ee]);const st=Object(c.m)(t=>{t.stopPropagation(),se({messageId:Ce,groupedId:e.groupedId})},[Ce,e.groupedId,se]),ct=Object(c.m)(e=>{const t=xe&&n&&n.messages?{messageId:Ce,childMessageIds:n.messages.map(({id:e})=>e),withShift:e&&e.shiftKey}:{messageId:Ce,withShift:e&&e.shiftKey};se(t)},[se,Ce,xe,n]),rt=Object(c.m)(()=>{ce({messageId:Ce})},[ce,Ce]),ot=Object(c.m)(e=>{e.stopPropagation()},[]),it=Object(c.m)(()=>{et&&(Object(m.kb)(et.id)?J({id:et.id}):Z({id:et.id}))},[et,J,Z]),lt=Object(c.m)(()=>{tt&&(Object(m.kb)(tt.id)?J({id:tt.id}):Z({id:tt.id}))},[tt,J,Z]),dt=Object(c.m)(()=>{v&&J({id:v.id})},[v,J]),bt=Object(c.m)(()=>{V({chatId:ye,threadId:H,messageId:e.replyToMessageId})},[V,ye,H,e.replyToMessageId]),ut=Object(c.m)(()=>{$({chatId:ye,threadId:H,messageId:Ce,origin:Me?l.h.ScheduledInline:l.h.Inline})},[ye,H,Ce,$,Me]),mt=Object(c.m)(()=>{Q({chatId:ye,messageId:Ce})},[ye,Ce,Q]),ht=Object(c.m)(e=>{$({chatId:ye,threadId:H,messageId:e,origin:Me?l.h.ScheduledAlbum:l.h.Album})},[ye,H,$,Me]),jt=Object(c.m)(()=>{ee({messageIds:[Ce]})},[Ce,ee]),gt=Object(c.m)(()=>{X({chatId:ye,messageId:Ce})},[X,ye,Ce]),ft=Object(c.m)(e=>{ae({chatId:ye,messageId:Ce,options:e})},[ye,Ce,ae]),pt=Object(c.m)(()=>{re({fromChatId:ye,groupedId:e.groupedId})},[re,ye,e.groupedId]),It=Object(c.m)(()=>{if(n&&n.messages){const e=n.messages.map(({id:e})=>e);re({fromChatId:ye,messageIds:e})}else re({fromChatId:ye,messageIds:[Ce]})},[n,re,ye,Ce]),Mt=Object(c.m)(()=>{V({chatId:ye,threadId:i.MAIN_THREAD_ID,messageId:Ce})},[V,ye,Ce]),St=Object(c.m)(()=>{V(Ae?{chatId:Ne.fromChatId,groupedId:e.groupedId,groupedChatId:ye}:{chatId:Ne.fromChatId,messageId:Ne.fromMessageId})},[V,Ne,e,ye,Ae]),kt=Object(te.a)();let Nt,Pt="";const Tt=Object(c.p)(()=>xe?Rt(Ee,Boolean(Te),n,be):void 0,[xe,be,Ee,Te,n]),At=Te?28:0;if(xe||!Le&&!Fe)Tt&&(Nt=Math.max(wt(Boolean(Re)),Tt.containerStyle.width));else{let t;Le?t=Et(e).width:Fe&&(t=Fe.isRound?Je.d:Et(e).width),t&&(Nt=Math.max(wt(Boolean(Re)),t))}Nt&&(Pt=`width: ${Nt+At}px`);const xt=Object(c.p)(()=>at?Ft(at):void 0,[at]),Lt=!(Ke||D||T)&&(!Ae||j),Ut=Lt&&x&&!Me,qt=Lt&&(Ne&&(Ne.isChannelPost||A&&!Ee)&&Ne.fromMessageId||G),Wt=e.threadInfo&&(!Ae||j)&&"thread"===q&&!d;return c.a.createElement("div",{ref:ie,id:"message"+Ce,className:Ye,style:xt?`--meta-safe-author-width: ${xt}px`:void 0,"data-message-id":Ce,onClick:D?ct:void 0,onDoubleClick:D?void 0:rt,onMouseDown:D?void 0:he,onContextMenu:D?void 0:Oe,onMouseEnter:Ae&&!j?xa:void 0,onMouseLeave:Ae&&!j?Ra:void 0},c.a.createElement("div",{ref:le,className:"bottom-marker","data-message-id":Ce,"data-last-message-id":n?n.messages[n.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!Ae&&c.a.createElement("div",{className:"message-select-control"},B&&c.a.createElement("i",{className:"icon-select"})),j&&c.a.createElement("div",{className:Object(K.a)("message-select-control group-select",U&&"is-selected"),onClick:st},U&&c.a.createElement("i",{className:"icon-select"})),r&&function(){const e=et&&Object(m.kb)(et.id),t=et&&e?et:void 0,a=et&&!e?et:void 0,s=!et&&Ne?Ne.hiddenUserName:void 0;return c.a.createElement(Bt.a,{size:"small",user:t,chat:a,text:s,lastSyncTime:R,onClick:t||a?it:void 0})}(),c.a.createElement("div",{className:"message-content-wrapper",onClick:D&&Ae?ct:void 0},c.a.createElement("div",{className:Xe,style:Pt},Xe.includes("has-appendix")&&c.a.createElement("div",{className:"svg-appendix",ref:de}),Te&&!$e&&(!Ae||O)&&c.a.createElement("div",{className:"message-title"},kt("ForwardedMessage")),function(){const t=Object(K.a)("content-inner",Te&&!$e&&"forwarded-message",Se&&"reply-message"),r=h&&!Qe&&!Te&&!ke;return c.a.createElement("div",{className:t,onDoubleClick:ot},function(){if($e||!(o&&!Le&&!Fe||Te||Pe||f)||Ae&&!O)return;let t,a;tt?(t=Object(m.U)(tt),Te||(a="color-"+Object(m.W)(tt))):Ne&&Ne.hiddenUserName&&(t=Ne.hiddenUserName);return c.a.createElement("div",{className:"message-title"},t?c.a.createElement("span",{className:Object(K.a)(tt&&"interactive",a),onClick:tt?lt:void 0},Object(Ze.a)(t)):v?void 0:" ",v&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"via"},kt("ViaBot")),c.a.createElement("span",{className:"interactive",onClick:dt},Object(Ze.a)("@"+v.username))),Ne&&Ne.isLinkedChannelPost?c.a.createElement("span",{className:"admin-title"},kt("DiscussChannel")):e.adminTitle&&!x?c.a.createElement("span",{className:"admin-title"},e.adminTitle):void 0)}(),Se&&c.a.createElement(Gt,{message:w,sender:E,observeIntersection:a,onClick:bt}),qe&&c.a.createElement(Yt,{message:e,observeIntersection:a,observeIntersectionForPlaying:s,shouldLoop:W,lastSyncTime:R}),F&&c.a.createElement(Jt.a,{isInline:!0,sticker:F,observeIntersection:a,lastSyncTime:R}),xe&&c.a.createElement(Sa,{album:n,albumLayout:Tt,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,isOwn:Ee,hasCustomAppendix:r,lastSyncTime:R,onMediaClick:ht}),!xe&&Le&&c.a.createElement(sa,{message:e,observeIntersection:a,shouldAutoLoad:_,uploadProgress:S,shouldAffectAppendix:r,onClick:ut,onCancelUpload:gt}),!xe&&Fe&&Fe.isRound&&c.a.createElement(Pa,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,lastSyncTime:R}),!xe&&Fe&&!Fe.isRound&&c.a.createElement(da,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:z,uploadProgress:S,lastSyncTime:R,onClick:ut,onCancelUpload:gt}),(De||Be)&&c.a.createElement(zt.a,{message:e,uploadProgress:S,lastSyncTime:R,isSelectable:Ae,isSelected:B,onPlay:mt,onReadMedia:!Be||Ee&&!A?void 0:jt,onCancelUpload:gt}),He&&c.a.createElement(_t.a,{message:e,observeIntersection:a,uploadProgress:S,isSelectable:Ae,isSelected:B,onCancelUpload:gt}),Ge&&c.a.createElement(ua,{contact:Ge}),_e&&c.a.createElement(pa,{message:e,poll:_e,onSendVote:ft}),!F&&Qe&&c.a.createElement("p",{className:"text-content"},Qe),We&&c.a.createElement(ya,{message:e,observeIntersection:a,shouldAutoLoad:_,onMediaClick:ut,onCancelMediaTransfer:gt}),Ve&&c.a.createElement(Ca,{message:e}))}(),(!Ae||j)&&c.a.createElement(Vt,{message:e,outgoingStatus:M,signature:at,onClick:ct}),Ut?c.a.createElement(ne.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Forward message",onClick:j?pt:It},c.a.createElement("i",{className:"icon-share-filled"})):qt?c.a.createElement(ne.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:G?Mt:St},c.a.createElement("i",{className:"icon-arrow-right"})):void 0,Wt&&c.a.createElement(Aa,{message:e,disabled:d})),e.inlineButtons&&c.a.createElement(Ta,{message:e,onClick:oe})),me&&c.a.createElement(Ht,{isOpen:ue,anchor:me,message:e,album:n,messageListType:q,onClose:je,onCloseAnimationEnd:ge}))}));a(226);const Da=h.b?1e3:350,Ba=h.f?300:500,Ua=Object(g.a)(e=>e(),200,!1),Ha=Object(g.j)(e=>e());var qa=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,type:s})=>{const n=Object(o.f)(e,t);if(!n)return{};const c=Object(o.x)(e,t,a,s),r="scheduled"===s?Object(o.nb)(e,t):Object(o.m)(e,t),l=Object(o.Bb)(e,t,a);if(a!==i.MAIN_THREAD_ID&&!(r&&l&&r[l]))return{};const{isRestricted:d,restrictionReason:b,lastMessage:u}=n,h=Object(o.H)(e,t),O=a===i.MAIN_THREAD_ID&&!c&&!n.unreadCount&&!h&&u&&!u.groupedId;let j;if(Object(o.K)(e,t)){const a=Object(o.g)(e,t);j=a.fullInfo?a.fullInfo.botDescription||"NoMessages":"Updating bot info..."}return{isChatLoaded:!0,isRestricted:d,restrictionReason:b,isChannelChat:Object(m.ib)(n),canPost:Object(m.e)(n,a),isChatWithSelf:Object(o.O)(e,t),messageIds:c,messagesById:r,firstUnreadId:Object(o.G)(e,t,a),isViewportNewest:"thread"!==s||Object(o.W)(e,t,a),threadFirstMessageId:Object(o.F)(e,t,a),focusingId:h,isSelectModeActive:Object(o.R)(e),animationLevel:e.settings.byKey.animationLevel,...O&&{lastMessage:u},botDescription:j,threadTopMessageId:l,hasLinkedChat:n.fullInfo&&"linkedChatId"in n.fullInfo?Boolean(n.fullInfo.linkedChatId):void 0}},(e,t)=>Object(d.l)(t,["loadViewportMessages","markMessageListRead","markMessagesRead","setScrollOffset"]))(({chatId:e,threadId:t,type:a,hasTools:r,onFabToggle:i,isChatLoaded:b,isChannelChat:u,canPost:O,bottomOffset:j,isChatWithSelf:f,messageIds:p,messagesById:I,firstUnreadId:v,isViewportNewest:y,threadFirstMessageId:C,isRestricted:w,restrictionReason:E,focusingId:M,isSelectModeActive:S,animationLevel:k,loadViewportMessages:N,markMessageListRead:P,markMessagesRead:T,setScrollOffset:x,lastMessage:R,botDescription:L,threadTopMessageId:F,hasLinkedChat:D})=>{const B=Object(c.q)(null),U=Object(c.q)("thread"===a&&Object(o.ob)(Object(s.e)(),e,t)||0),H=Object(c.q)(),q=Object(c.q)(),G=Object(c.q)(),_=Object(c.q)(v),z=Object(c.q)(),W=Object(c.q)(),V=Object(c.q)(!1),$=Object(c.q)(!p),[Y,J]=Object(c.r)(),[Z,X]=Object(c.r)(Boolean(M)),ee=Boolean(p);Object(me.a)(()=>{ee&&Object(g.d)(()=>{$.current=!1})},[ee]),Object(me.a)(()=>{z.current=v},[v]);const{observe:ae,freeze:se,unfreeze:ne}=Object(Ot.a)({rootRef:B,throttleMs:Da,margin:Ba}),{observe:ce,freeze:re,unfreeze:oe}=Object(Ot.a)({rootRef:B},e=>{if("thread"!==a)return;let t=0;const s=[];e.forEach(e=>{const{isIntersecting:a,target:n}=e;if(!a)return;const{dataset:c}=n,r=Number(c.lastMessageId||c.messageId);r>t&&(t=r),c.hasUnreadMention&&s.push(r)}),z.current&&t>=z.current&&P({maxId:t}),s.length&&T({messageIds:s})});Object(me.a)(()=>{W.current=M,M?(se(),re()):(oe(),ne())},[M]);const{observe:ie}=Object(Ot.a)({rootRef:B,throttleMs:Da});Object(c.n)(()=>{M?X(!0):setTimeout(()=>{X(!1)},200)},[M]);const le=Object(c.p)(()=>{if(!p||!I)return;const e=!F||p[0]&&C!==p[0]?p:[F,...p];if(!e.length)return;const t=e.map(e=>I[e]);return ht(Object(d.k)(t,["date","id"]),_.current)},[p,I,C,F]),[de,be,ue]=Object(c.p)(()=>"thread"===a?[Object(g.a)(()=>N({direction:l.e.Backwards}),1e3,!0,!1),Object(g.a)(()=>N({direction:l.e.Forwards}),1e3,!0,!1),Object(g.a)(()=>N({direction:l.e.Around}),1e3,!0,!1)]:[],[N,p]),{isScrolled:he,updateStickyDates:Oe}=jt(),je=Object(c.m)(()=>{if(V.current)return void(V.current=!1);const s=B.current;W.current||Oe(s,r),Ua(()=>{Object(g.b)(()=>{s.parentElement&&(U.current=s.scrollHeight-s.scrollTop,"thread"===a&&x({chatId:e,threadId:t,scrollOffset:U.current}))})})},[Oe,r,a,x,e,t]);Object(c.n)(()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver(([e])=>{e.target.offsetParent&&J(e.contentRect.height)});return e.observe(B.current),()=>{e.disconnect()}},[]),Object(c.o)(()=>{B.current.dataset.normalHeight=String(B.current.offsetHeight)},[]),Object(c.o)(()=>{h.d&&Ha(()=>{if(!B.current.querySelector(".AnimatedSticker.is-playing"))return;const e=B.current.style;e.webkitOverflowScrolling="auto"===e.webkitOverflowScrolling?"":"auto"})}),Object(c.n)(()=>{if(!ue||!b||w||M)return;const e=B.current;(!p||p.length{const s=B.current;if(G.current=Array.from(s.querySelectorAll(".message-list-item")),!s.offsetParent)return;const c=y&&p&&p.length{s.parentElement&&s.parentElement.classList.remove("force-messages-scroll")},1e3));const{scrollTop:o,scrollHeight:i,offsetHeight:l}=s,d=U.current,b=G.current[G.current.length-1],u=b?b.offsetHeight:0,m=y&&t&&d-(a||l)-u<=100;let h;const O=p&&e&&p[0]!==e[0],j=p&&e&&p[p.length-1]!==e[e.length-1],f=p&&W.current===p[p.length-1];if(m&&j&&!O&&!f&&(b&&Object(g.b)(()=>{Object(ft.a)(s,b,"end",20,void 0,void 0,void 0,!0)}),h=i-l,U.current=Math.max(i-h,l),!c))return;const I=void 0!==a&&a!==Y,v=H.current&&s.querySelector("#"+H.current),C=!v&&_.current&&s.querySelector(".unread-divider");if(m&&I){if(Object(ft.b)())return;h=i-l}else if(v){h=o+(v.getBoundingClientRect().top-(q.current||0))}else h=C?C.offsetTop-(r?60:10):i-d;Object(gt.a)(s,h),W.current||(V.current=!0,Object(g.b)(()=>{V.current=!1})),U.current=Math.max(i-h,l)},[p,y,Y,r]),Object(c.n)(()=>{(!k||k>0)&&Object(Q.b)(200+n.c)},[k,S]);const ge=Object(te.a)(),fe=Boolean(e&&Object(m.kb)(e)),pe=Boolean(!fe&&!u||f),Ie=Object(K.a)("MessageList custom-scroll",!pe&&"no-avatars",u&&"no-avatars",(!O||"none"!==j)&&"bottom-padding","none"!==j&&"bottom-padding-"+j,S&&"select-mode-active",Z&&"has-focusing",he&&"scrolled");return c.a.createElement("div",{ref:B,className:Ie,onScroll:je},w?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,E?E.text:"This is a private "+(u?"channel":"chat"))):L?c.a.createElement("div",{className:"empty rich"},c.a.createElement("span",null,Object(Ze.a)(ge(L),["br","emoji","links"]))):p&&!le?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,ge("NoMessages"))):p&&le||R?c.a.createElement(It,{containerRef:B,className:"messages-container",messageIds:p||[R.id],containerHeight:Y,listItemElementsRef:G,focusingId:M,anchorIdRef:H,anchorTopRef:q,loadMoreForwards:be,loadMoreBackwards:de,isViewportNewest:y,firstUnreadId:v,onFabToggle:i},function(e,t,a,s,r,o,i,l,b,u,h,O,j,g=!1,f=!1){const p=c.a.createElement("div",{className:Object(K.a)("unread-divider","local-action-message"),key:"unread-messages"},c.a.createElement("span",null,e("UnreadMessages"))),I=f?0:t.reduce((e,t)=>e+Object(d.h)(t.senderGroups).length,0);let v=0;const y=t.map((t,f,y)=>{const C=t.senderGroups.map((t,n,g)=>{if(1===t.length&&!mt(t[0])&&Object(m.cb)(t[0])){const e=t[0];return Object(d.e)([e.id===l.current&&p,c.a.createElement(qt,{key:e.id,message:e,observeIntersection:a,appearanceOrder:I-++v})])}let C;return Object(d.h)(t.map((w,E)=>{const M=mt(w)?w.mainMessage:w,S=mt(w)?w:void 0,k=Object(m.sb)(M),N=mt(w),P=t[E+1];M.previousLocalId&&i.current==="message"+M.previousLocalId&&(i.current="message"+M.id);const T=!N&&M.groupedId?M.groupedId:void 0,A=P&&!mt(P)?P.groupedId:void 0,x={isFirstInGroup:0===E,isLastInGroup:E===t.length-1,isFirstInDocumentGroup:Boolean(T&&T!==C),isLastInDocumentGroup:Boolean(T&&T!==A),isLastInList:E===t.length-1&&n===g.length-1&&f===y.length-1};C=T;const R=M.id===l.current&&l.current!==O||M.id===h&&l.current===O,L=Object(m.F)(M),F="scheduled"!==u?L:`${M.date}_${L}`;return Object(d.e)([R&&p,c.a.createElement(Fa,{key:F,message:M,observeIntersectionForBottom:a,observeIntersectionForMedia:s,observeIntersectionForAnimatedStickers:r,album:S,withAvatar:x.isLastInGroup&&o&&!k&&!(M.id===h),withSenderName:x.isFirstInGroup&&o&&!k,threadId:b,messageListType:u,noComments:!1===j,appearanceOrder:I-++v,isFirstInGroup:x.isFirstInGroup,isLastInGroup:x.isLastInGroup,isFirstInDocumentGroup:x.isFirstInDocumentGroup,isLastInDocumentGroup:x.isLastInDocumentGroup,isLastInList:x.isLastInList}),M.id===h&&c.a.createElement("div",{className:"local-action-message",key:"discussion-started"},c.a.createElement("span",null,e("DiscussionStarted")))])}))});return c.a.createElement("div",{className:"message-date-group",key:t.datetime,teactFastList:!0},c.a.createElement("div",{className:"sticky-date",key:"date-header"},c.a.createElement("span",null,g&&t.originalDate===n.kb&&e("MessageScheduledUntilOnline"),g&&t.originalDate!==n.kb&&e("MessageScheduledOn",Object(A.c)(t.datetime,void 0,!0)),!g&&Object(A.c)(t.datetime))),Object(d.h)(C))});return Object(d.h)(y)}(ge,le||ht([R]),ce,ae,ie,pe,H,_,t,a,F,C,D,!!le&&"scheduled"===a,!le||!$.current)):c.a.createElement(ve.a,{color:"white"}))}));a(227);var Ga=Object(c.h)(Object(s.h)(e=>{const t=Object(o.y)(e);if(!t)return{};const{chatId:a,threadId:s,type:n}=t,c=Object(o.f)(e,a);return{messageListType:n,canPost:c&&Object(m.e)(c,s),unreadCount:c&&s===i.MAIN_THREAD_ID&&"thread"===n?c.unreadCount:void 0}},(e,t)=>Object(d.l)(t,["focusLastMessage"]))(({isShown:e,messageListType:t,canPost:a,unreadCount:s,focusLastMessage:n})=>{const r=Object(c.q)(null),o=Object(c.m)(()=>{if(e)if("thread"===t)n();else{const e=r.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),a=t[t.length-1];if(!a)return;Object(ft.a)(e,a,"end",20)}},[e,t,n]),i=Object(K.a)("ScrollDownButton",e&&"revealed",!a&&"no-composer");return c.a.createElement("div",{ref:r,className:i},c.a.createElement("div",{className:"ScrollDownButton-inner"},c.a.createElement(ne.a,{color:"secondary",round:!0,onClick:o,ariaLabel:"Scroll to bottom"},c.a.createElement("i",{className:"icon-arrow-down"})),Boolean(s)&&c.a.createElement("div",{className:"unread-count"},Object(Ve.b)(s))))})),_a=a(126),za=a(127),Wa=a(14);async function Va(e,t,a,s){const n=URL.createObjectURL(t),{type:c,size:r}=t;let o,i;if(c.startsWith("image/"))if(a){const a=await Object(Wa.g)(n),{width:r,height:i}=a;if(r>1280||i>1280||"image/jpeg"!==c){const c=await function(e){return new Promise(t=>{const a=document.createElement("canvas"),s=a.getContext("2d");let{width:n,height:c}=e;(n>1280||c>1280)&&(n>=c?(c*=1280/n,n=1280):(n*=1280/c,c=1280)),a.width=n,a.height=c,s.drawImage(e,0,0,e.width,e.height,0,0,n,c),a.toBlob(t,"image/jpeg",100)})}(a);return c?(URL.revokeObjectURL(n),Va(e,c,!0,s)):Va(e,t,!1,s)}o={width:r,height:i}}else i=n;else if(c.startsWith("video/")){if(r<10485760){const{videoWidth:e,videoHeight:t,duration:a}=await Object(Wa.h)(n);o={width:e,height:t,duration:a}}i=await Object(Wa.c)(n)}return{blobUrl:n,filename:e,mimeType:c,size:r,quick:o,previewBlobUrl:i,...s}}var $a=a(171),Qa=a.p+"8ccc0b555efcec3616377aea078dda16.js";const Ka={encoderPath:Qa,reuseWorker:!0},Ya={type:"audio/ogg"};let Ja,Za,Xa;async function es(){return Ja||(Ja=a.e(9).then(a.t.bind(null,305,7)),Za=(await Ja).default,Xa=new Za(Ka)),Ja}async function ts(e){await async function(){await es(),await Xa.start()}();const t=Date.now();let a;const s=[],n=[];Xa.ondataavailable=e=>{s.push(e)};const c=function(e,t){const a=e.sourceNode,s=a.context.createAnalyser();s.fftSize=64,a.connect(s);const n=s.frequencyBinCount,c=new Uint8Array(n);let r=!1;return function e(){if(r)return;s.getByteFrequencyData(c);const a=c.reduce((e,t)=>e+t,0),o=a/n/255;t(o<.1?0:o),requestAnimationFrame(e)}(),()=>{r=!0}}(Xa,t=>{n.push(255*t),e(t)});return{stop:()=>new Promise((e,r)=>{Xa.onstop=()=>{e({blob:new Blob(s,Ya),duration:Math.round(((a||Date.now())-t)/1e3),waveform:n})},Xa.onerror=r;const o=Math.max(0,t+1e3-Date.now());setTimeout(()=>{Xa.stop(),c()},o)}),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout(()=>{Xa.pause(),a=Date.now(),c()},e)}}}const as=["image/png","image/jpeg","image/gif"];function ss(e){const{text:t,entities:a}=e||{};if(!t)return"";const s=Object(yt.b)(t,a,void 0,void 0,!0);return Array.isArray(s)?s.join(""):s}let ns,cs;var rs=a(58);var os=a(180);var is=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"DeleteMessageModal",!t);return a?c.a.createElement(a,e):void 0};function ls(){return(ls=Object.assign||function(e){for(var t=1;t{const a=Object(c.q)(!1),s=Object(c.m)(()=>{if(a.current=!0,bs)return bs=!1,void e();ds&&(clearTimeout(ds),ds=void 0),ds=window.setTimeout(()=>{a.current&&e()},200)},[e]),n=Object(c.m)(()=>{a.current=!1},[]);return c.a.createElement(ne.a,ls({},t,{onMouseEnter:h.k?void 0:s,onMouseLeave:h.k?void 0:n,onClick:h.k?e:void 0}))});var ms=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"AttachMenu",!t);return a?c.a.createElement(a,e):void 0};var hs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"SymbolMenu",!t);return a?c.a.createElement(a,e):void 0};var Os=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"MentionMenu",!t);return a?c.a.createElement(a,e):void 0};var js=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"CustomSendMenu",!t);return a?c.a.createElement(a,e):void 0};var gs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"EmojiTooltip",!t);return a?c.a.createElement(a,e):void 0};var fs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"BotKeyboardMenu",!t);return a?c.a.createElement(a,e):void 0},ps=a(172),Is=a(109);a(229);var vs=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a,type:s}=Object(o.y)(e)||{};if(!t||!a||!s)return{};const{currentUserId:n,forwardMessages:{fromChatId:c,toChatId:r,messageIds:i}}=e,l=Object(o.jb)(e,t,a),d="scheduled"===s?Object(o.E)(e,t):Object(o.C)(e,t,a),b=e.settings.byKey.animationLevel>=1,u=r===t;let h,O;if(l?h=Object(o.k)(e,t,l):d?h=Object(o.D)(e,t,a,s):u&&1===i.length&&(h=Object(o.k)(e,c,i[0])),l&&h){const{forwardInfo:a}=h,s=t===n;a&&(a.isChannelPost||s)&&(O=Object(o.J)(e,h)),O||(O=Object(o.qb)(e,h))}else u&&(O=Object(m.kb)(c)?Object(o.Db)(e,c):Object(o.f)(e,c));return{replyingToId:l,editingId:d,message:h,sender:O,shouldAnimate:b,forwardedMessagesCount:u?i.length:void 0}},(e,t)=>Object(d.l)(t,["setReplyingToId","setEditingId","focusMessage","exitForwardMode"]))(({replyingToId:e,editingId:t,message:a,sender:s,shouldAnimate:n,forwardedMessagesCount:r,setReplyingToId:o,setEditingId:i,focusMessage:l,exitForwardMode:d})=>{const b=Boolean((e||t)&&a||s&&r),u=Object(Is.a)([r],r?300:void 0),{shouldRender:m,transitionClassNames:h}=Object(Y.a)(u&&b,void 0,!n,void 0,!n),O=Object(c.m)(()=>{e?o({messageId:void 0}):t?i({messageId:void 0}):r&&d()},[e,t,r,o,i,d]);Object(c.n)(()=>b?Object(Z.a)(O):void 0,[b,O]);const j=Object(c.m)(()=>{l({chatId:a.chatId,messageId:a.id})},[l,a]),g=Object(K.a)("ComposerEmbeddedMessage",h),f=r&&r>1?r+" forwarded messages":void 0;if(m)return c.a.createElement("div",{className:g},c.a.createElement("div",null,c.a.createElement(ne.a,{round:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:O},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(Gt,{className:"inside-input",message:a,sender:s,customText:f,title:t?"Edit Message":void 0,onClick:j})))}));var ys=e=>{const{attachments:t}=e,a=Object(Ie.a)(pe.a.Extra,"AttachmentModal",!t.length);return a?c.a.createElement(a,e):void 0};var Cs=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"PollModal",!t);return a?c.a.createElement(a,e):void 0};var ws=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"DropArea",!t);return a?c.a.createElement(a,e):void 0};a(230);const Es=new RegExp(n.fb,"i");var Ms=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a})=>{const s=Object(o.bb)(e,t,a);return{webPagePreview:e.webPagePreview,noWebPage:s}},(e,t)=>Object(d.l)(t,["loadWebPagePreview","clearWebPagePreview","toggleMessageWebPage"]))(({chatId:e,threadId:t,messageText:a,disabled:s,webPagePreview:n,noWebPage:r,loadWebPagePreview:o,clearWebPagePreview:l,toggleMessageWebPage:d})=>{const b=Object(c.p)(()=>{const{text:e,entities:t}=Object(za.a)(a),s=t&&t.find(({type:e})=>e===i.ApiMessageEntityTypes.TextUrl);if(s)return s.url;const n=e.match(Es);return n?n[0]:void 0},[a]);Object(c.n)(()=>{b?o({text:b}):(l(),d({chatId:e,threadId:t}))},[e,d,l,b,o,t]),Object(me.a)(()=>{l(),d({chatId:e,threadId:t})},[e]);const u=Boolean(n&&a.length&&!r&&!s),{shouldRender:m,transitionClassNames:h}=Object(Y.a)(u),O=qe(n);if(!m||!O)return;const{photo:j,...g}=O,f={content:{webPage:g}};return c.a.createElement("div",{className:Object(K.a)("WebPagePreview",h)},c.a.createElement("div",null,c.a.createElement(ne.a,{round:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{d({chatId:e,threadId:t,noWebPage:!0})}},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(ya,{message:f,inPreview:!0})))})),Ss=a(113);var ks=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"CalendarModal",!t);return a?c.a.createElement(a,e):void 0};var Ns=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"PaymentModal",!t);return a?c.a.createElement(a,e):void 0};var Ps,Ts=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ReceiptModal",!t);return a?c.a.createElement(a,e):void 0};a(231);!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(Ps||(Ps={}));var As=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=n&&Object(o.o)(e,n),r=n?Object(o.N)(e,n):void 0,l=Object(o.O)(e,t),d=r&&Object(o.ab)(e,t),b=Object(o.lb)(e,t);return{editingMessage:Object(o.D)(e,t,a,s),connectionState:e.connectionState,draft:Object(o.B)(e,t,a),chat:n,isChatWithBot:r,isChatWithSelf:l,canScheduleUntilOnline:!l&&!r&&n&&c&&Object(m.kb)(t)&&c.status&&Boolean(c.status.wasOnline),isRightColumnShown:Object(o.V)(e),isSelectModeActive:Object(o.R)(e),withScheduledButton:a===i.MAIN_THREAD_ID&&"thread"===s&&Boolean(b&&b.length),shouldSchedule:"scheduled"===s,botKeyboardMessageId:d?d.id:void 0,isForwarding:t===e.forwardMessages.toChatId,canSuggestMembers:n&&Object(m.jb)(n),isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:n&&n.fullInfo&&n.fullInfo.members,currentUserId:e.currentUserId,usersById:e.users.byId,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),shouldSuggestStickers:e.settings.byKey.shouldSuggestStickers}},(e,t)=>Object(d.l)(t,["sendMessage","editMessage","saveDraft","clearDraft","showError","setStickerSearchQuery","setGifSearchQuery","forwardMessages","openPollModal","closePollModal","closePaymentModal","clearReceipt","loadScheduledHistory","openChat"]))(({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:a,onDropHide:r,editingMessage:o,chatId:l,threadId:d,messageListType:b,draft:u,chat:O,connectionState:j,isChatWithBot:f,isChatWithSelf:p,isRightColumnShown:I,isSelectModeActive:v,isForwarding:y,canSuggestMembers:C,isPollModalOpen:w,isPaymentModalOpen:E,isReceiptModalOpen:M,botKeyboardMessageId:S,withScheduledButton:k,stickersForEmoji:N,groupChatMembers:P,currentUserId:T,usersById:x,lastSyncTime:R,contentToBeScheduled:L,shouldSuggestStickers:F,sendMessage:D,editMessage:B,saveDraft:U,clearDraft:H,showError:q,setStickerSearchQuery:G,setGifSearchQuery:_,forwardMessages:z,openPollModal:W,closePollModal:V,loadScheduledHistory:$,closePaymentModal:Q,openChat:Y,clearReceipt:J})=>{const X=Object(c.q)(null),[ee,ae]=Object(c.r)(""),se=Object(c.q)(),ce=Object(He.a)(e),[re,oe,ie]=Object(nt.a)(),[le,be]=Object(c.r)(),ue=Object(c.q)(ee);Object(c.n)(()=>{ue.current=ee},[ee]),Object(c.n)(()=>{se.current=void 0},[l]),Object(c.n)(()=>{l&&R&&d===i.MAIN_THREAD_ID&&$()},[l,$,R,d]),Object(c.o)(()=>{X.current&&(X.current.innerHTML='')},[]),Object(c.n)(()=>{L&&(be(L),oe())},[L,oe]);const[me,he]=Object(c.r)([]),[Oe,je,ge]=Object(nt.a)(),[fe,pe,Ie]=Object(nt.a)(),[ve,ye,Ce]=Object(nt.a)(),[we,Ee,Me]=Object(nt.a)(),[Se,ke]=Object(nt.a)(),[Ne,Pe,Te]=Object(nt.a)(),{startRecordingVoice:Ae,stopRecordingVoice:xe,pauseRecordingVoice:Re,activeVoiceRecording:Le,currentRecordTime:De,recordButtonRef:Be,startRecordTimeRef:Ue}=(()=>{const e=Object(c.q)(null),[t,a]=Object(c.r)(),s=Object(c.q)(),[n,r]=Object(c.r)();Object(c.n)(()=>{h.d&&es()},[]);const o=Object(c.m)(async()=>{try{const{stop:t,pause:n}=await ts(t=>{e.current&&(s.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))});s.current=Date.now(),r(Date.now()),a({stop:t,pause:n})}catch(e){console.error(e)}},[]),i=Object(c.m)(()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}},[t]),l=Object(c.m)(()=>{if(t){a(void 0),s.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}},[t]);return Object(c.n)(()=>t?Object(Z.a)(l):void 0,[t,l]),{startRecordingVoice:o,pauseRecordingVoice:i,stopRecordingVoice:l,activeVoiceRecording:t,currentRecordTime:n,recordButtonRef:e,startRecordTimeRef:s}})(),qe=o?Ps.Edit:!h.l||Le||ee&&!me.length||y?Ps.Send:Ps.Record,Ge=!t,{isMentionMenuOpen:_e,mentionFilter:ze,closeMentionMenu:We,insertMention:Ve,mentionFilteredMembers:$e}=Object(os.a)(C&&!me.length,ee,ae,void 0,P,T,x),{isContextMenuOpen:Qe,handleContextMenu:Ke,handleContextMenuClose:Ye,handleContextMenuHide:Je}=Object(vt.a)(Be,!(qe===Ps.Send&&Ge)),Xe=Object(c.p)(()=>Object(m.c)(O,f),[O,f]),et=O&&Object(m.fb)(O),tt=Object(m.k)(O),{isEmojiTooltipOpen:at,closeEmojiTooltip:st}=function(e,t,a){const{loadStickersForEmoji:n,clearStickersForEmoji:r}=Object(s.d)(),o=h.c&&1===Object(rs.a)(t)||!h.c&&Boolean(t.match(/^]*?>$/g)),i=Boolean(a)&&o;return Object(c.n)(()=>{e&&o?n({emoji:t}):!i&&o||r()},[t,o,r,n,e]),{isEmojiTooltipOpen:i,closeEmojiTooltip:r}}(Boolean(F&&Xe.canSendStickers&&!me.length),ee,N),ct=Object(c.m)(e=>{const t=window.getSelection(),a=document.getElementById(n.u),s=Object(Ze.a)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(t.rangeCount){const n=t.getRangeAt(0);if(Object($a.a)(n))return void(h.c?document.execCommand("insertText",!1,e):(!function(e){const t=window.getSelection();if(t&&t.getRangeAt&&t.rangeCount){const a=t.getRangeAt(0);a.deleteContents();const s=a.createContextualFragment(e),n=s.lastChild;a.insertNode(s),n&&(a.setStartAfter(n),a.setEndAfter(n),t.removeAllRanges(),t.addRange(a))}}(s),a.dispatchEvent(new Event("input",{bubbles:!0}))));ae(`${ue.current}${s}`),h.f||requestAnimationFrame(()=>{Object(_a.a)(a)})}else ae(`${ue.current}${s}`)},[]),rt=Object(c.m)(()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if(Object($a.a)(t))return void document.execCommand("delete",!1)}ae(function(e){const t=document.createElement("div");t.contentEditable="true",t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t);let a=t.lastChild;if(a.lastChild)for(;a.lastChild;)a=a.lastChild;const s=a.textContent.length,n=document.createRange(),c=window.getSelection();n.setStart(a,s),n.setEnd(a,s),c.removeAllRanges(),c.addRange(n),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(ue.current))},[]),ot=Object(c.m)(()=>{ae(""),he([]),st(),ie(),be(void 0),We(),h.f?setTimeout(()=>Ce(),350):Ce()},[st,ie,We,Ce]),it=Object(He.a)(l);Object(c.n)(()=>{it&&l!==it&&(xe(),ot())},[l,it,ot,xe]);const lt=((e,t,a,s,r,o)=>{Object(c.n)(()=>{a?(t(ss(a.content.text)),requestAnimationFrame(()=>{const e=document.getElementById(n.u);Object(_a.a)(e,!0)})):t("")},[a,t]);return Object(c.m)(()=>{const{text:t,entities:n}=Object(za.a)(e.current);a&&(t||Object(m.bb)(a)?(o({messageId:a.id,text:t,entities:n}),s()):r())},[o,a,e,r,s])})(ue,ae,o,ot,Ee,B);((e,t,a,s,r,o,i,l,d)=>{const b=Object(c.m)((e,t)=>{r.current.length&&!i?l({chatId:e,threadId:t,draft:Object(za.a)(r.current)}):d({chatId:e,threadId:t})},[d,i,r,l]),u=Object(c.p)(()=>Object(g.a)(e=>e(),n.t,!1),[t]),m=Object(He.a)(t),h=Object(He.a)(a);Object(c.n)(()=>(ns=t,cs=a,()=>{ns=void 0,cs=void 0,b(t,a)}),[t,a,b]),Object(c.n)(()=>{t===m&&a===h||e&&(o(ss(e)),requestAnimationFrame(()=>{const e=document.getElementById(n.u);Object(_a.a)(e,!0)}))},[t,a,e,o,b,m,h]);const O=Object(He.a)(s);Object(c.n)(()=>{t&&a&&m===t&&h===a&&O!==s&&(s.length?u(()=>{ns===t&&cs===a&&b(t,a)}):b(t,a))},[t,s,m,O,h,u,a,b]),Object(c.n)(()=>{function e(){t&&a&&b(t,a)}return window.addEventListener("blur",e),()=>{window.removeEventListener("blur",e)}},[t,a,b])})(u,l,d,ee,ue,ae,o,U,H),((e,t,a)=>{Object(c.n)(()=>{async function s(s){if(!s.clipboardData)return;const c=document.activeElement;if(c&&"INPUT"===c.tagName&&![n.u,n.v].includes(c.id))return;const{items:r}=s.clipboardData,o=Array.from(r).find(e=>as.includes(e.type)),i=o&&o.getAsFile(),l=s.clipboardData.getData("text").substring(0,4096);if(i||l){if(s.preventDefault(),i&&!a){const e=await Va(i.name,i,!0);t(t=>[...t,e])}l&&e(l)}}return document.addEventListener("paste",s,!1),()=>{document.removeEventListener("paste",s,!1)}},[e,a,t])})(ct,he,o);const dt=Object(c.m)(async(e,t)=>{he(await Promise.all(e.map(e=>Va(e.name,e,t))))},[]),bt=Object(c.m)(()=>{he([])},[]),ut=Object(c.m)(async(e=!1,t)=>{if("connectionStateReady"!==j)return;let a=me;if(Le){const e=await xe();if(e){const{blob:t,duration:s,waveform:n}=e;a=[await Va("wonderful-voice-message.ogg",t,!1,{voice:{duration:s,waveform:n}})]}}const{text:s,entities:c}=Object(za.a)(ue.current);if(a.length||s||y)if(a.length&&s&&s.length>1024){const e=s.length-1024;q({error:{message:"CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""}}})}else{if(a.length||s){if(tt&&!et){const e=Math.floor(Date.now()/1e3),t=se.current&&Math.floor(e-se.current),a=tt.nextSendDate&&tt.nextSendDate>e;if(t&&t{e={...e,isPreloadedGlobally:!0},t?(be({sticker:e}),oe()):(D({sticker:e}),requestAnimationFrame(ot))},[t,oe,D,ot]),ht=Object(c.m)(e=>{t?(be({gif:e}),oe()):(D({gif:e}),requestAnimationFrame(ot))},[t,oe,D,ot]),Ot=Object(c.m)(e=>{t?(be({poll:e}),V(),oe()):(D({poll:e}),V())},[V,oe,D,t]),jt=Object(c.m)(()=>{t?(be({isSilent:!0}),oe()):ut(!0)},[ut,oe,t]),gt=Object(c.m)(e=>{const{isSilent:t,...a}=le||{},s=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3);le&&0!==Object.keys(a).length?(D({...le,scheduledAt:s}),requestAnimationFrame(ot)):ut(!!t,s),ie()},[ie,ut,ot,le,D]),ft=Object(c.m)(()=>{gt(new Date(1e3*n.kb))},[gt]),pt=Object(c.m)(()=>{ie(),be(void 0)},[ie]),It=Object(c.m)(e=>{"stickers"===e?(G({query:""}),_({query:void 0})):(_({query:""}),G({query:void 0}))},[G,_]),yt=Object(c.m)(()=>{const e=document.getElementById(n.u);h.f&&e===document.activeElement?(e.blur(),setTimeout(()=>{ye()},100)):ye()},[ye]),Ct=Object(c.m)(()=>{Y({id:l,threadId:d,type:"scheduled"})},[Y,l,d]);Object(c.n)(()=>{I&&h.f&&Ce()},[I,Ce]),Object(c.n)(()=>{v?Pe():setTimeout(()=>{Te()},200)},[v,Te,Pe]);const wt=Object(c.m)(()=>{switch(qe){case Ps.Send:t?(Le&&Re(),oe()):(ut(),requestAnimationFrame(ot));break;case Ps.Record:Ae();break;case Ps.Edit:lt()}},[qe,ot,t,Ae,lt,Le,oe,Re,ut]),Et=Object(te.a)(),Mt=qe===Ps.Record&&!Xe.canAttachMedia,St=Object(He.a)(o,!0),kt=o||St,Nt=new Date;Nt.setSeconds(0),Nt.setMilliseconds(0);const Pt=new Date;Pt.setFullYear(Pt.getFullYear()+1);let Tt="Send message";switch(qe){case Ps.Edit:Tt="Save edited message";break;case Ps.Record:Tt=Mt?"Posting media content is not allowed in this group.":"Record a voice message"}const At=Object(K.a)("Composer",!v&&"shown",Ne&&"hover-disabled"),xt=Object(K.a)("mobile-symbol-menu-button",Se?ve&&"menu-opened":ve&&"is-loading");return c.a.createElement("div",{className:At},Xe.canAttachMedia&&c.a.createElement(Ss.a,{containerId:"#middle-column-portals"},c.a.createElement(ws,{isOpen:e!==Fe.a.None,withQuick:[e,ce].includes(Fe.a.QuickFile),onHide:r,onFileSelect:dt})),c.a.createElement(ys,{attachments:me,caption:me.length?ee:"",canSuggestMembers:C,groupChatMembers:P,currentUserId:T,usersById:x,onCaptionUpdate:ae,onSend:t?oe:ut,onClear:bt}),c.a.createElement(Cs,{isOpen:Boolean(w),onClear:V,onSend:Ot}),c.a.createElement(Ns,{isOpen:Boolean(E),onClose:Q}),c.a.createElement(Ts,{isOpen:Boolean(M),onClose:J}),kt&&c.a.createElement(is,{isOpen:we,isSchedule:"scheduled"===b,onClose:Me,message:kt}),c.a.createElement(Os,{isOpen:_e,filter:ze,onClose:We,onInsertUserName:Ve,filteredChatMembers:$e,usersById:x}),c.a.createElement("div",{id:"message-compose"},c.a.createElement("div",{className:"svg-appendix",ref:X}),c.a.createElement(vs,null),c.a.createElement(Ms,{chatId:l,threadId:d,messageText:me.length?"":ee,disabled:!Xe.canAttachEmbedLinks}),c.a.createElement("div",{className:"message-input-wrapper"},h.f?c.a.createElement(ne.a,{className:xt,round:!0,color:"translucent",onClick:ve?Ce:yt,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"}),c.a.createElement("i",{className:"icon-keyboard"}),c.a.createElement(de.a,{color:"gray"})):c.a.createElement(us,{className:""+(ve?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:ye,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"})),c.a.createElement(ps.a,{id:"message-input-text",html:me.length?"":ee,placeholder:Le&&window.innerWidth<=600?"":Et("Message"),shouldSetFocus:ve,shouldSupressFocus:h.f&&ve,onUpdate:ae,onSend:qe===Ps.Edit?lt:t?oe:ut,onSupressedFocus:Ce}),k&&c.a.createElement(ne.a,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:Ct,ariaLabel:"Open scheduled messages"},c.a.createElement("i",{className:"icon-schedule"})),S&&!Le&&!o&&c.a.createElement(us,{className:""+(Oe?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:je,ariaLabel:"Open bot command keyboard"},c.a.createElement("i",{className:"icon-bot-command"})),!Le&&!o&&c.a.createElement(us,{className:""+(fe?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:pe,ariaLabel:"Add an attachment"},c.a.createElement("i",{className:"icon-attach"})),Le&&De&&c.a.createElement("span",{className:"recording-state"},Object(A.i)(De-Ue.current)),c.a.createElement(gs,{isOpen:at,onStickerSelect:mt}),c.a.createElement(ms,{isOpen:fe,allowedAttachmentOptions:Xe,onFileSelect:dt,onPollCreate:W,onClose:Ie}),S&&c.a.createElement(fs,{messageId:S,isOpen:Oe,onClose:ge}),c.a.createElement(hs,{isOpen:ve,allowedAttachmentOptions:Xe,onLoad:ke,onClose:Ce,onEmojiSelect:ct,onStickerSelect:mt,onGifSelect:ht,onRemoveSymbol:rt,onSearchOpen:It}))),Le&&c.a.createElement(ne.a,{round:!0,color:"danger",className:"cancel",onClick:xe,ariaLabel:"Cancel voice recording"},c.a.createElement("i",{className:"icon-delete"})),c.a.createElement(ne.a,{ref:Be,round:!0,color:"secondary",className:`${qe} ${Le?"recording":""}`,disabled:Mt,ariaLabel:Tt,onClick:wt,onContextMenu:qe===Ps.Send&&Ge?Ke:void 0},c.a.createElement("i",{className:"icon-send"}),c.a.createElement("i",{className:"icon-microphone-alt"}),c.a.createElement("i",{className:"icon-check"})),Ge&&c.a.createElement(js,{isOpen:Qe,onSilentSend:p?void 0:jt,onScheduleSend:t?void 0:oe,onClose:Ye,onCloseAnimationEnd:Je}),c.a.createElement(ks,{isOpen:re,withTimePicker:!0,selectedAt:Nt.getTime(),maxAt:Object(A.k)(Pt),isFutureMode:!0,secondButtonLabel:a?"Send When Online":void 0,onClose:pt,onSubmit:gt,onSecondButtonClick:a?ft:void 0}))}));var xs=e=>{const{isActive:t}=e,a=Object(Ie.a)(pe.a.Extra,"MobileSearch",!t,!0);return a?c.a.createElement(a,e):void 0};var Rs=e=>{const{isActive:t}=e,a=Object(Ie.a)(pe.a.Extra,"MessageSelectToolbar",!t);return a?c.a.createElement(a,e):void 0};var Ls=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"UnpinAllMessagesModal",!t);return a?c.a.createElement(a,e):void 0};a(232);const Fs=h.f?450+n.c:void 0;function Ds(e){return"file"===e.kind&&e.type&&n.k.includes(e.type)}var Bs=Object(c.h)(Object(s.h)(e=>{const{isBackgroundBlurred:t,customBackground:a,patternColor:s}=e.settings.byKey,n=Boolean((a||"").match(/^#[a-f\d]{6,8}$/i)),c=Object(o.y)(e),{chats:{listIds:r}}=e;if(!c||!r.active)return{customBackground:a,isBackgroundBlurred:t,isCustomBackgroundColor:n};const{chatId:i,threadId:l,type:d}=c,b=Object(o.f)(e,i),u=Object(o.gb)(e,i),{chatId:O,messageId:j}=e.audioPlayer,g=b&&Object(m.e)(b,l),f=Object(o.K)(e,i),p="pinned"===d;return{chatId:i,threadId:l,messageListType:d,isPrivate:Object(m.kb)(i),canPost:!p&&(!b||g)&&(!f||h.f),isPinnedMessageList:p,messageSendingRestrictionReason:b&&Object(m.J)(b),hasPinnedOrAudioMessage:Boolean(u&&u.length)||Boolean(O&&j),customBackground:a,patternColor:s,isCustomBackgroundColor:n,isRightColumnShown:Object(o.V)(e),isBackgroundBlurred:t,isMobileSearchActive:Boolean(h.f&&Object(o.A)(e)),isSelectModeActive:Object(o.R)(e),animationLevel:e.settings.byKey.animationLevel}},(e,t)=>Object(d.l)(t,["openChat","unpinAllMessages","loadUser"]))(({chatId:e,threadId:t,messageListType:a,isPrivate:s,isPinnedMessageList:r,canPost:o,messageSendingRestrictionReason:l,hasPinnedOrAudioMessage:d,customBackground:b,patternColor:u,isCustomBackgroundColor:m,isRightColumnShown:O,isBackgroundBlurred:j,isMobileSearchActive:g,isSelectModeActive:f,animationLevel:p,openChat:I,unpinAllMessages:v,loadUser:y})=>{const{width:C}=Ue(),[w,E]=Object(c.r)(Fe.a.None),[M,S]=Object(c.r)(!1),[k,N]=Object(c.r)(!1),P=qe(e,Fs),T=qe(t,Fs),A=qe(a,Fs),x=qe(o,Fs);Object(c.n)(()=>e?Object(Z.a)(()=>{I({id:void 0})}):void 0,[e,I]),Object(c.n)(()=>{E(Fe.a.None)},[e]),Object(c.n)(()=>{s&&y({userId:e})},[e,s,y]);const R=Object(c.m)(e=>{if(h.k)return;const{items:t}=e.dataTransfer||{},a=t&&Array.from(t).every(Ds);E(a?Fe.a.QuickFile:Fe.a.Document)},[]),L=Object(c.m)(()=>{E(Fe.a.None)},[]),F=Object(c.m)(()=>{N(!0)},[]),D=Object(c.m)(()=>{N(!1)},[]),B=Object(c.m)(()=>{v({chatId:e}),D(),I({id:e})},[v,I,D,e]),U=(e=>{const[t,a]=Object(c.r)(e);return Object(c.n)(()=>{e&&(e.startsWith("#")?a(e):De.c(n.l,n.l,De.a.Blob).then(e=>{a("url("+URL.createObjectURL(e))}))},[e]),t})(b),H=d&&(Cn.Z&&C=n.Y&&CGe(C,x),[x,C]),Y=Object(te.a)();return c.a.createElement("div",{id:"MiddleColumn",className:q,style:`\n --composer-hidden-scale: ${_};\n --toolbar-hidden-scale: ${z};\n --unpin-hidden-scale: ${$};\n --toolbar-unpin-hidden-scale: ${Q};\n --composer-translate-x: ${W}px;\n --toolbar-translate-x: ${V}px;\n --pattern-color: ${u};\n `},c.a.createElement("div",{id:"middle-column-bg",style:U?"--custom-background: "+U:void 0}),c.a.createElement("div",{id:"middle-column-portals"}),P&&T&&c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"messages-layout",onDragEnter:x?R:void 0},c.a.createElement(bt,{chatId:P,threadId:T,messageListType:A}),c.a.createElement(X.a,{name:p===n.e?"slide":"fade",activeKey:"thread"===A&&T===i.MAIN_THREAD_ID?1:2,shouldCleanup:!0},()=>c.a.createElement(c.a.Fragment,null,c.a.createElement(qa,{key:`${P}-${T}-${A}`,chatId:P,threadId:T,type:A,hasTools:H,onFabToggle:S,bottomOffset:x?"none":r?"big":"small"}),c.a.createElement("div",{className:Object(K.a)("middle-column-footer",!x&&"no-composer")},x&&c.a.createElement(As,{chatId:P,threadId:T,messageListType:A,dropAreaState:w,onDropHide:L}),r&&c.a.createElement("div",{className:"unpin-button-container"},c.a.createElement(ne.a,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:F},c.a.createElement("i",{className:"icon-unpin"}),c.a.createElement("span",null,Y("Chat.PanelHidePinnedMessages")))),!r&&!x&&l&&c.a.createElement("div",{className:G},c.a.createElement("div",{className:"messaging-disabled-inner"},c.a.createElement("span",null,l))),c.a.createElement(Rs,{messageListType:A,isActive:f,canPost:x})))),c.a.createElement(Ga,{isShown:M})),h.f&&c.a.createElement(xs,{isActive:Boolean(g)})),e&&c.a.createElement(Ls,{isOpen:k,chatId:e,onClose:D,onUnpin:B}))}));a(233);const Us=Object(g.a)(e=>e(),200,!1);var Hs;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupMembers=16]="ManageGroupMembers",e[e.StickerSearch=17]="StickerSearch",e[e.GifSearch=18]="GifSearch",e[e.PollResults=19]="PollResults"}(Hs||(Hs={}));var qs=Object(c.h)(Object(s.h)((e,{chatId:t,isProfile:a,isManagement:s})=>{const{query:n}=Object(o.A)(e)||{},{query:c}=Object(o.z)(e)||{},{query:r}=Object(o.s)(e)||{},i=t?Object(o.f)(e,t):void 0,l=i&&Object(m.ib)(i);return{canManage:Boolean(!s&&a&&i&&!Object(o.O)(e,i.id)&&(Object(m.kb)(i.id)||(Object(m.fb)(i)||i.isCreator)&&!i.isNotJoined)),isChannel:l,messageSearchQuery:n,stickerSearchQuery:c,gifSearchQuery:r}},(e,t)=>Object(d.l)(t,["setLocalTextSearchQuery","setStickerSearchQuery","setGifSearchQuery","searchTextMessagesLocal","toggleManagement","searchMessagesByDate"]))(({isColumnOpen:e,isProfile:t,isSearch:a,isManagement:s,isStickerSearch:n,isGifSearch:r,isPollResults:o,profileState:i,managementScreen:d,canManage:b,isChannel:u,onClose:m,messageSearchQuery:O,stickerSearchQuery:j,gifSearchQuery:g,setLocalTextSearchQuery:f,setStickerSearchQuery:p,setGifSearchQuery:I,searchTextMessagesLocal:v,toggleManagement:y,searchMessagesByDate:C})=>{var w;const E=Object(c.q)(null),[M,S,k]=Object(nt.a)(),N=Object(c.m)(e=>{f({query:e}),e.length&&Us(v)},[v,f]),P=Object(c.m)(e=>{C({timestamp:e.valueOf()/1e3}),k()},[k,C]),T=Object(c.m)(e=>{p({query:e})},[p]),A=Object(c.m)(e=>{I({query:e})},[I]),[x,R]=Object(c.r)(!e);Object(c.n)(()=>{setTimeout(()=>{R(!e)},300)},[e]);const L=Object(te.a)(),F=t?i===l.k.Profile?Hs.Profile:i===l.k.SharedMedia?Hs.SharedMedia:i===l.k.MemberList?Hs.MemberList:-1:a?Hs.Search:o?Hs.PollResults:n?Hs.StickerSearch:r?Hs.GifSearch:s?d===l.g.Initial?Hs.ManageInitial:d===l.g.ChatPrivacyType?Hs.ManageChatPrivacyType:d===l.g.Discussion?Hs.ManageDiscussion:d===l.g.ChannelSubscribers?Hs.ManageChannelSubscribers:d===l.g.GroupPermissions?Hs.ManageGroupPermissions:d===l.g.ChatAdministrators?Hs.ManageChatAdministrators:d===l.g.GroupRemovedUsers?Hs.ManageGroupRemovedUsers:d===l.g.GroupUserPermissionsCreate?Hs.ManageGroupUserPermissionsCreate:d===l.g.GroupUserPermissions?Hs.ManageGroupUserPermissions:d===l.g.GroupRecentActions?Hs.ManageGroupRecentActions:d===l.g.ChatAdminRights?Hs.ManageGroupAdminRights:d===l.g.GroupMembers?Hs.ManageGroupMembers:void 0:void 0,D=null!==(w=We(F,!0))&&void 0!==w?w:-1;function B(){if(-1!==D)switch(D){case Hs.PollResults:return c.a.createElement("h3",null,L("PollResults"));case Hs.Search:return c.a.createElement(c.a.Fragment,null,c.a.createElement(ce.a,{value:O,onChange:N}),c.a.createElement(ne.a,{round:!0,size:"smaller",color:"translucent",onClick:S,ariaLabel:"Search messages by date"},c.a.createElement("i",{className:"icon-calendar"})));case Hs.ManageInitial:return c.a.createElement("h3",null,L("Edit"));case Hs.ManageChatPrivacyType:return c.a.createElement("h3",null,L(u?"ChannelTypeHeader":"GroupTypeHeader"));case Hs.ManageDiscussion:return c.a.createElement("h3",null,L("Discussion"));case Hs.ManageChatAdministrators:return c.a.createElement("h3",null,L("ChannelAdministrators"));case Hs.ManageGroupRecentActions:return c.a.createElement("h3",null,L("Group.Info.AdminLog"));case Hs.ManageGroupAdminRights:return c.a.createElement("h3",null,L("EditAdminRights"));case Hs.ManageGroupPermissions:return c.a.createElement("h3",null,L("ChannelPermissions"));case Hs.ManageGroupRemovedUsers:return c.a.createElement("h3",null,L("ChannelBlockedUsers"));case Hs.ManageGroupUserPermissionsCreate:return c.a.createElement("h3",null,L("ChannelAddException"));case Hs.ManageGroupUserPermissions:return c.a.createElement("h3",null,L("UserRestrictions"));case Hs.StickerSearch:return c.a.createElement(ce.a,{value:j,placeholder:"Search Stickers",onChange:T});case Hs.GifSearch:return c.a.createElement(ce.a,{value:g,placeholder:L("SearchGifsTitle"),onChange:A});case Hs.SharedMedia:return c.a.createElement("h3",null,L("SharedMedia"));case Hs.ManageChannelSubscribers:return c.a.createElement("h3",null,L("ChannelSubscribers"));case Hs.MemberList:case Hs.ManageGroupMembers:return c.a.createElement("h3",null,L("GroupMembers"));default:return c.a.createElement(c.a.Fragment,null,c.a.createElement("h3",null,"Profile"),c.a.createElement("section",{className:"tools"},b&&c.a.createElement(ne.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:L("Edit"),onClick:y},c.a.createElement("i",{className:"icon-edit"}))))}}const U=h.f||F===Hs.SharedMedia||F===Hs.MemberList||s,H=Object(K.a)("animated-close-icon",x&&"no-transition");return Object(c.n)(()=>{E.current.classList.toggle("state-back",U)},[U]),c.a.createElement("div",{className:"RightHeader"},c.a.createElement(ne.a,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:m,ariaLabel:L(U?"Common.Back":"Common.Close")},c.a.createElement("div",{ref:E,className:H})),c.a.createElement(X.a,{name:x?"none":"slide-fade",activeKey:D},B),!h.f&&c.a.createElement(ks,{isOpen:M,isPastMode:!0,submitButtonLabel:L("JumpToDate"),onClose:k,onSubmit:P}))})),Gs=a(118);function _s(e,t,a,s,r,o,i,l,d,b,u){const h="members"!==s&&r?r:s,O=Object(c.p)(()=>{if(o&&i)return Object(m.Cb)(o.map(({userId:e})=>e),i)},[o,i]),[j,g,f]=function(e,t,a,s){const[c,r]=Object(Gs.a)(a?t:void 0,s,void 0,n.Q),o=!c||!s||c[0]===s[0];return[c,r,!o]}(0,t,u,O),[p,I,v]=zs("media",h,a,u,l,d),[y,C,w]=zs("documents",h,a,u,l,d),[E,M,S]=zs("links",h,a,u,l,d),[k,N,P]=zs("audio",h,a,u,l,d);let T,A,x=!1;switch(h){case"members":T=j,A=g,x=f;break;case"media":T=p,A=I,x=v;break;case"documents":T=y,A=C,x=w;break;case"links":T=E,A=M,x=S;break;case"audio":T=k,A=N,x=P}return[h,T,A,x]}function zs(e,t,a,s,r,o){const i=Object(c.q)();Object(me.a)(()=>{t===e&&r&&o&&(i.current=Object(m.w)(r,o,e).reverse())},[r,o,t,e]);const[l,d]=Object(Gs.a)(s?a:void 0,i.current,void 0,"media"===e?n.mb:n.W);return[l,d,!(!l||!i.current||l[0]===i.current[0])]}var Ws=a(52);const Vs=Object(g.g)(e=>e(),250,!1);let $s=!1;var Qs=a(102),Ks=a(95);var Ys=a(123),Js=a(173);a(234);var Zs=Object(c.h)(({chat:e,user:t,photo:a,isFirstPhoto:s,isSavedMessages:n,lastSyncTime:r,onClick:o})=>{const l=t&&Object(m.ob)(t);function d(s="big",c){if(a&&!c)return`photo${a.id}?size=c`;let r;return n||l||(t?r=Object(m.f)(t,s):e&&(r=Object(m.f)(e,s))),r}const b=d(),u=Object(Xe.a)(b,!1,i.ApiMediaFormat.BlobUrl,r),h=Object(Xe.a)(!u&&s?d("normal",!0):void 0,!1,i.ApiMediaFormat.BlobUrl,r),O=Object(Js.a)(!u&&a&&a.thumbnail&&a.thumbnail.dataUri),j=u||h||O,g=Object(He.a)(j);let f="";if(n)f=c.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(l)f=c.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(j)f=c.a.createElement("img",{src:j,className:"avatar-media",alt:"",decoding:"async"});else if(!j&&t){const e=Object(m.Y)(t);f=e?Object(Ve.c)(e,2):void 0}else if(!j&&e){const t=Object(m.l)(e);f=t&&Object(Ve.c)(t,Object(m.kb)(e.id)?2:1)}else f=c.a.createElement("div",{className:"spinner-wrapper"},c.a.createElement(de.a,{color:"white"}));const p=Object(K.a)("ProfilePhoto","color-bg-"+Object(m.W)(t||e),n&&"saved-messages",l&&"deleted-account",!n&&!j&&"no-photo");return c.a.createElement("div",{className:p,onClick:j?o:void 0},g&&j&&g!==j&&c.a.createElement("img",{src:g,className:"prev-avatar-media",alt:"",decoding:"async"}),"string"==typeof f?Object(Ze.a)(f,["hq_emoji"]):f)});a(235);var Xs=Object(c.h)(Object(s.h)((e,{userId:t,forceShowSelf:a})=>{const{lastSyncTime:s}=e,n=Object(o.Db)(e,t),c=Object(o.f)(e,t),r=!a&&n&&n.isSelf,{animationLevel:i}=e.settings.byKey;return{lastSyncTime:s,user:n,chat:c,isSavedMessages:r,animationLevel:i}},(e,t)=>Object(d.l)(t,["loadFullUser","openMediaViewer"]))(({user:e,chat:t,isSavedMessages:a,lastSyncTime:s,animationLevel:n,loadFullUser:r,openMediaViewer:o})=>{const{id:d}=e||{},{id:b}=t||{},u=e?Object(m.Y)(e):t?t.title:"",O=(e?e.photos:t?t.photos:void 0)||[],j=n>=1?"slide":"none",[g,f]=Object(c.r)(0),p=a||O.length<=1||0===g,I=a||O.length<=1||g===O.length-1;Object(c.n)(()=>{g>O.length&&f(Math.max(0,O.length-1))},[g,O.length]);const v=Object(te.a)();Object(c.n)(()=>{s&&d&&r({userId:d})},[d,r,s]),function(e,t,a){Object(c.n)(()=>{t.slice(a,a+4).forEach(e=>{it.c(`photo${e.id}?size=c`)||it.b(`photo${e.id}?size=c`,i.ApiMediaFormat.BlobUrl)})},[a,t])}(0,O,g);const y=Object(c.m)(()=>{o({avatarOwnerId:d||b,profilePhotoIndex:g,origin:l.h.ProfileAvatar})},[o,d,b,g]),C=Object(c.m)(()=>{p||f(g-1)},[g,p]),w=Object(c.m)(()=>{I||f(g+1)},[g,I]);if(Object(c.n)(()=>{const e=document.querySelector(".profile-slide-container > .active, .profile-slide-container > .to");if(e)return Object(ue.b)(e,{excludedClosestSelector:".navigation",onSwipe:h.k?(e,t)=>{t===ue.a.Right?C():t===ue.a.Left&&w()}:void 0})},[w,C]),!e&&!t)return;function E(){const s=!a&&O&&O.length>0?O[g]:void 0;return c.a.createElement(Zs,{key:g,user:e,chat:t,photo:s,isSavedMessages:a,isFirstPhoto:p,onClick:y})}const M=e&&e.isVerified||t&&t.isVerified;return c.a.createElement("div",{className:"ProfileInfo"},c.a.createElement("div",{className:"photo-wrapper"},function(){if(!(a||!O||O.length<=1))return c.a.createElement("div",{className:"photo-dashes"},O.map((e,t)=>c.a.createElement("span",{className:"photo-dash "+(t===g?"current":"")})))}(),c.a.createElement(X.a,{activeKey:g,name:j,className:"profile-slide-container"},E),!p&&c.a.createElement("button",{type:"button",className:"navigation prev","aria-label":v("AccDescrPrevious"),onClick:C}),!I&&c.a.createElement("button",{type:"button",className:"navigation next","aria-label":v("Next"),onClick:w})),c.a.createElement("div",{className:"info"},a?c.a.createElement("div",{className:"title"},c.a.createElement("h3",null,v("SavedMessages"))):c.a.createElement("div",{className:"title"},c.a.createElement("h3",null,u&&Object(Ze.a)(u)),M&&c.a.createElement(Ys.a,null)),!a&&(e?c.a.createElement("div",{className:"status "+(Object(m.wb)(e)?"online":"")},c.a.createElement("span",{className:"user-status"},Object(m.Z)(e,v))):c.a.createElement("span",{className:"status"},Object(m.ib)(t)?v("Subscribers",t.membersCount,"i"):v("Members",t.membersCount,"i")))))}));var en=Object(c.h)(Object(s.h)((e,{chatOrUserId:t})=>{const{lastSyncTime:a}=e,s=t?Object(o.f)(e,t):void 0;return{lastSyncTime:a,chat:s,user:Object(m.kb)(t)?Object(o.Db)(e,t):void 0,canInviteUsers:s&&(!Object(m.ib)(s)&&!Object(m.xb)(s,"inviteUsers")||Object(m.q)(s,"inviteUsers"))}},(e,t)=>Object(d.l)(t,["loadFullUser","updateChatMutedState","showNotification"]))(({lastSyncTime:e,user:t,chat:a,forceShowSelf:s,canInviteUsers:n,loadFullUser:r,showNotification:o,updateChatMutedState:i})=>{const{id:l,fullInfo:d,username:b,phoneNumber:u,isSelf:h}=t||{},{id:O,isMuted:j,username:g}=a||{},f=Object(te.a)();Object(c.n)(()=>{e&&l&&r({userId:l})},[r,l,e]);const p=Object(c.m)((e,t)=>{Object(w.c)(e),o({message:t+" was copied"})},[o]),I=Object(c.m)(()=>{i({chatId:O,isMuted:!j})},[O,j,i]);if(!a||a.isRestricted||h&&!s)return;const v=d&&d.bio,y=u&&Object(ba.c)(u),C=Object(m.g)(a),E=Object(m.h)(a),M=0===E.indexOf("http")?E:"http://"+E,S=b||g,k=v||C;return c.a.createElement("div",{className:"ChatExtra"},y&&!!y.length&&c.a.createElement(Ks.a,{icon:"phone",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(y,f("Phone"))},c.a.createElement("span",{className:"title"},y),c.a.createElement("span",{className:"subtitle"},f("Phone"))),S&&c.a.createElement(Ks.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p("@"+S,f("Username"))},c.a.createElement("span",{className:"title"},Object(Ze.a)(S)),c.a.createElement("span",{className:"subtitle"},f("Username"))),k&&!!k.length&&c.a.createElement(Ks.a,{icon:"info",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(k,f(l?"UserBio":"Info"))},c.a.createElement("span",{className:"title"},Object(Ze.a)(k,["br","links","emoji"])),c.a.createElement("span",{className:"subtitle"},f(l?"UserBio":"Info"))),n&&!S&&!!E.length&&c.a.createElement(Ks.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>p(E,f("SetUrlPlaceholder"))},c.a.createElement("div",{className:"title"},c.a.createElement(va.a,{url:M,className:"title",text:E})),c.a.createElement("span",{className:"subtitle"},f("SetUrlPlaceholder"))),c.a.createElement(Ks.a,{icon:"unmute",onClick:I},c.a.createElement("span",null,f("Notifications")),c.a.createElement(oe,{id:"group-notifications",label:""+(l?"Toggle User Notifications":"Toggle Chat Notifications"),checked:!j,inactive:!0})))})),tn=a(155),an=a(174),sn=a(108);a(239);const nn=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"}];function cn(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > div.active > .${e}-list > .scroll-item`].join(", ")}var rn=Object(c.h)(Object(s.h)((e,{chatId:t,userId:a})=>{const s=Object(o.f)(e,t),n=Object(o.m)(e,a||t),{currentType:c,resultsByType:r}=Object(o.v)(e)||{},{foundIds:i}=r&&c&&r[c]||{},{byId:l}=e.users,d=s&&Object(m.jb)(s),b=s&&Object(m.ib)(s),u=d||b&&Object(m.fb)(s),h=s&&s.fullInfo&&s.fullInfo.members,O=u&&s&&s.fullInfo&&!s.fullInfo.canViewMembers;let j;return a?j=a:Object(m.kb)(t)&&(j=t),{isChannel:b,resolvedUserId:j,chatMessages:n,foundIds:i,mediaSearchType:c,hasMembersTab:u,areMembersHidden:O,...u&&h&&{members:h,usersById:l},isRightColumnShown:Object(o.V)(e),isRestricted:s&&s.isRestricted,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(d.l)(t,["setLocalMediaSearchType","loadMoreMembers","searchMediaMessagesLocal","openMediaViewer","openAudioPlayer","openUserInfo","focusMessage","loadProfilePhotos"]))(({chatId:e,profileState:t,onProfileStateChange:a,isChannel:s,resolvedUserId:r,chatMessages:o,foundIds:d,mediaSearchType:b,hasMembersTab:u,areMembersHidden:m,members:O,usersById:j,isRightColumnShown:g,isRestricted:f,lastSyncTime:p,setLocalMediaSearchType:I,loadMoreMembers:v,searchMediaMessagesLocal:y,openMediaViewer:C,openAudioPlayer:w,openUserInfo:E,focusMessage:M,loadProfilePhotos:S})=>{const k=Object(c.q)(null),N=Object(c.q)(null),[P,T]=Object(c.r)(0),A=Object(c.p)(()=>[...u?[{type:"members",title:s?"ChannelSubscribers":"GroupMembers"}]:[],...nn],[u,s]),x=A[P].type,[R,L,F,D]=_s(0,v,y,x,b,O,j,o,d,0,p),B=A.findIndex(({type:e})=>e===R),{handleScroll:U}=function(e,t,a,s){Object(Ws.a)(([a])=>{if(a&&a!==t){const a=e.current,n=a.querySelector(".TabList");a.scrollTop{$s=!1},350))}},[t,s]),Object(Ws.a)(([t])=>{if(a!==l.k.Profile||a===t)return;const n=e.current;if(!n)return;const c=n.querySelector(".TabList");!c||c.offsetTop>n.scrollTop||($s=!0,Object(ft.a)(n,n.firstElementChild,"start",void 0,2*n.offsetHeight),setTimeout(()=>{$s=!1},350),s(a))},[a]);const n=Object(c.m)(()=>{const a=e.current;if(!a)return;const n=a.querySelector(".TabList");if(!n)return;let c=l.k.Profile;a.scrollTop>=n.offsetTop&&(c="members"===t?l.k.MemberList:l.k.SharedMedia),s(c)},[e,s,t]);return Object(c.n)(()=>{$s||n()},[n,t]),{handleScroll:Object(c.m)(()=>{$s||Vs(n)},[n])}}(k,x,t,a),{applyTransitionFix:H,releaseTransitionFix:q}=function(e,t=".Transition.shared-media-transition"){return Object(c.n)(()=>{function a(){const a=e.current,s=a.querySelector(t),n=a.querySelector(".TabList");s&&n&&(s.style.minHeight=a.offsetHeight-n.offsetHeight+"px")}return a(),window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[e,t]),{applyTransitionFix:Object(c.m)(()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=e+"px"}},[e]),releaseTransitionFix:Object(c.m)(()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"},[e])}}(k),[G,_]=(()=>{const[e,t]=Object(c.r)(!1);return[e,Object(c.m)(()=>{t(e=>!e)},[])]})(),z=Object(c.m)(()=>{q(),_()},[q,_]);Object(c.n)(()=>{I({mediaType:x})},[I,x]);const W=r||e;Object(c.n)(()=>{p&&S({profileId:W})},[S,W,p]);const V=Object(c.m)(e=>{C({chatId:W,threadId:i.MAIN_THREAD_ID,messageId:e,origin:l.h.SharedMedia})},[W,C]),$=Object(c.m)(e=>{w({chatId:W,messageId:e})},[W,w]),Q=Object(c.m)(e=>{E({id:e})},[E]),K=Object(c.m)(e=>{M({chatId:W,messageId:e})},[W,M]);let Y;Object(c.n)(()=>{if(N.current&&h.k)return Object(ue.b)(N.current,{onSwipe:(e,t)=>{t===ue.a.Left?T(Math.min(P+1,A.length-1)):t===ue.a.Right&&T(Math.max(0,P-1))}})},[P,A.length]);const J="members"===R||!u&&"media"===R;J?Y=g?0:1e3:L||(Y=n.nb);const Z=Object(Is.a)([e,R],Y);function ee(){if(!L||!Z||!o){const e=J&&L&&!Z;return c.a.createElement("div",{className:"content empty-list"},!e&&c.a.createElement(de.a,null))}if(!L.length){let e;switch(R){case"members":e=m?"You have no access to group members list.":"No members found";break;case"documents":e="No documents found.";break;case"links":e="No links found.";break;case"audio":e="No audio found.";break;default:e="No media found."}return c.a.createElement("div",{className:"content empty-list"},c.a.createElement(sn.a,{text:e}))}return c.a.createElement("div",{className:`content ${R}-list`,teactFastList:!0},"media"===R?L.map(e=>o[e]&&c.a.createElement(tn.a,{key:e,message:o[e],onClick:V})):"documents"===R?L.map(e=>o[e]&&c.a.createElement(_t.a,{key:e,message:o[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:K})):"links"===R?L.map(e=>o[e]&&c.a.createElement(an.a,{key:e,message:o[e],onMessageClick:K})):"audio"===R?L.map(e=>o[e]&&c.a.createElement(zt.a,{key:e,renderingFor:"sharedMedia",message:o[e],date:o[e].date,lastSyncTime:p,className:"scroll-item",onPlay:$,onDateClick:K})):"members"===R?L.map((e,t)=>c.a.createElement(Ks.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>Q(e)},c.a.createElement($e.a,{userId:e,forceShowSelf:!0}))):void 0)}return c.a.createElement(Qs.a,{ref:k,className:"Profile custom-scroll",itemSelector:cn(R),items:Z?L:void 0,cacheBuster:G,sensitiveArea:n.eb,preloadBackwards:Z?"members"===R?n.Q:n.mb:0,noFastList:!0,onLoadMore:F,onScroll:U},!D&&function(e,t){return c.a.createElement("div",{className:"profile-info"},c.a.createElement(Xs,{userId:t||e,forceShowSelf:t!==e}),c.a.createElement(en,{chatOrUserId:t||e,forceShowSelf:t!==e}))}(e,r),!f&&c.a.createElement("div",{className:"shared-media"},c.a.createElement(X.a,{ref:N,name:"slide",activeKey:B,renderCount:A.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:H,onStop:z},ee),c.a.createElement(je.a,{activeTab:P,tabs:A,onSwitchTab:T})))}));var on=e=>{const t=Object(Ie.a)(pe.a.Extra,"RightSearch");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var ln=e=>{const t=Object(Ie.a)(pe.a.Extra,"Management");return t?c.a.createElement(t,e):c.a.createElement(ve.a,null)};var dn=()=>{const e=Object(Ie.a)(pe.a.Extra,"StickerSearch");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};var bn=()=>{const e=Object(Ie.a)(pe.a.Extra,"GifSearch");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};var un=()=>{const e=Object(Ie.a)(pe.a.Extra,"PollResults");return e?c.a.createElement(e,null):c.a.createElement(ve.a,null)};a(240);const mn=Object.keys(l.l).length/2,hn=Object.keys(l.g).length/2;function On(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}var jn=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},s=Object(o.d)(e);return{contentKey:Object(o.kb)(e),chatId:t,threadId:a,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&s)}},(e,t)=>Object(d.l)(t,["openUserInfo","toggleChatInfo","toggleManagement","closeLocalTextSearch","setStickerSearchQuery","setGifSearchQuery","closePollResults"]))(({contentKey:e,chatId:t,threadId:a,currentProfileUserId:s,isChatSelected:r,toggleChatInfo:o,toggleManagement:i,openUserInfo:d,closeLocalTextSearch:b,setStickerSearchQuery:u,setGifSearchQuery:m,closePollResults:h})=>{var O;const{width:j}=Ue(),[g,f]=Object(c.r)(l.k.Profile),[p,I]=Object(c.r)(l.g.Initial),[v,y]=Object(c.r)(),[C,w]=Object(c.r)(),E=g!==l.k.Profile,M=void 0!==e,S=e===l.l.ChatInfo||e===l.l.UserInfo,k=e===l.l.Search,N=e===l.l.Management,P=e===l.l.StickerSearch,T=e===l.l.GifSearch,A=e===l.l.PollResults,x=j<=n.Z,[R,L]=Object(c.r)(!M),F=null!==(O=We(e,!0,!r))&&void 0!==O?O:-1,D=Object(c.m)(()=>{switch(e){case l.l.ChatInfo:if(E){f(l.k.Profile);break}o();break;case l.l.UserInfo:if(E){f(l.k.Profile);break}d({id:void 0});break;case l.l.Management:switch(p){case l.g.Initial:i();break;case l.g.ChatPrivacyType:case l.g.Discussion:case l.g.GroupPermissions:case l.g.GroupType:case l.g.ChatAdministrators:case l.g.ChannelSubscribers:case l.g.GroupMembers:I(l.g.Initial);break;case l.g.GroupUserPermissionsCreate:case l.g.GroupRemovedUsers:case l.g.GroupUserPermissions:I(l.g.GroupPermissions),y(void 0),w(void 0);break;case l.g.ChatAdminRights:case l.g.GroupRecentActions:I(l.g.ChatAdministrators)}break;case l.l.Search:On(),b();break;case l.l.StickerSearch:case l.l.GifSearch:On(),u({query:void 0}),m({query:void 0});break;case l.l.PollResults:h()}},[e,E,o,d,h,p,i,b,u,m]),B=Object(c.m)((e,t)=>{y(e),w(t)},[]);function U(){if(-1!==F)switch(F){case l.l.ChatInfo:case l.l.UserInfo:return c.a.createElement(rn,{key:s||t,chatId:t,userId:s,profileState:g,onProfileStateChange:f});case l.l.Search:return c.a.createElement(on,{chatId:t,threadId:a});case l.l.Management:return c.a.createElement(ln,{chatId:t,currentScreen:p,isPromotedByCurrentUser:C,selectedChatMemberId:v,onScreenSelect:I,onChatMemberSelect:B});case l.l.StickerSearch:return c.a.createElement(dn,null);case l.l.GifSearch:return c.a.createElement(bn,null);case l.l.PollResults:return c.a.createElement(un,null)}}return Object(c.n)(()=>M?Object(Z.a)(D):void 0,[M,D]),Object(c.n)(()=>{setTimeout(()=>{L(!M)},300)},[M]),Object(c.n)(()=>{M&&x&&D()},[x]),Object(ut.a)(([a,s])=>{(a===l.l.ChatInfo&&e===l.l.UserInfo||a===l.l.UserInfo&&e===l.l.ChatInfo||s!==t)&&(f(l.k.Profile),I(l.g.Initial))},[e,t]),c.a.createElement("div",{id:"RightColumn-wrapper",className:r?void 0:"is-hidden"},x&&c.a.createElement("div",{className:"overlay-backdrop",onClick:D}),c.a.createElement("div",{id:"RightColumn"},c.a.createElement(qs,{chatId:t,isColumnOpen:M,isProfile:S,isSearch:k,isManagement:N,isStickerSearch:P,isGifSearch:T,isPollResults:A,profileState:g,managementScreen:p,onClose:D}),c.a.createElement(X.a,{name:R?"none":"zoom-fade",renderCount:mn+hn,activeKey:N?mn+p:F},U)))}));var gn=Object(c.h)(({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"MediaViewer",!e);return t?c.a.createElement(t,null):void 0});var fn=({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"Notifications",!e);return t?c.a.createElement(t,null):void 0};var pn=({isOpen:e})=>{const t=Object(Ie.a)(pe.a.Extra,"Errors",!e);return t?c.a.createElement(t,null):void 0};var In=e=>{const{isOpen:t}=e,a=Object(Ie.a)(pe.a.Extra,"ForwardPicker",!t);return a?c.a.createElement(a,e):void 0};a(241);let vn,yn,Cn=!1;function wn(e){document.querySelectorAll('link[rel="icon"]').forEach(t=>{e?t.href.includes("favicon-unread")||(t.href=t.href.replace("favicon","favicon-unread")):t.href=t.href.replace("favicon-unread","favicon")})}var En=Object(c.h)(Object(s.h)(e=>{const{chatId:t,messageId:a}=e.audioPlayer,s=t&&a?Object(o.k)(e,t,a):void 0;return{animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:Object(o.V)(e),isMediaViewerOpen:Object(o.S)(e),isForwardModalOpen:Object(o.Q)(e),hasNotifications:Boolean(e.notifications.length),hasErrors:Boolean(e.errors.length),audioMessage:s}},(e,t)=>Object(d.l)(t,["loadAnimatedEmojis"]))(({lastSyncTime:e,loadAnimatedEmojis:t,isLeftColumnShown:a,isRightColumnShown:r,isMediaViewerOpen:i,isForwardModalOpen:l,animationLevel:d,hasNotifications:b,hasErrors:u,audioMessage:m})=>{n.o&&!Cn&&(Cn=!0,console.log(">>> RENDER MAIN")),Object(c.n)(()=>{e&&t()},[e,t]);const{transitionClassNames:h}=Object(Y.a)(!a,void 0,!0),{transitionClassNames:O}=Object(Y.a)(r,void 0,!0),j=Object(K.a)(h.replace(/([\w-]+)/g,"middle-column-$1"),O.replace(/([\w-]+)/g,"right-column-$1"));function g(e){e.preventDefault(),e.stopPropagation()}return Object(c.n)(()=>{document.body.classList.toggle("is-middle-column-open",j.includes("middle-column-open")),document.body.classList.toggle("is-right-column-shown",j.includes("right-column-open"))},[j]),Object(c.n)(()=>{d>0&&(document.body.classList.add("animating-right-column"),Object(Q.b)(350+n.c),vn&&(clearTimeout(vn),vn=void 0),vn=window.setTimeout(()=>{document.body.classList.remove("animating-right-column"),vn=void 0},350+n.c))},[d,r]),Object(J.a)(()=>{const e=Object(o.q)(Object(s.e)());let t=0;clearInterval(yn),yn=window.setInterval(()=>{if(document.title.includes(n.D))wn(!1);else{if(t%2==0){const t=Object(o.q)(Object(s.e)())-e;t>0&&(document.title=`${t} notification${t>1?"s":""}`,wn(!0))}else document.title=n.db,wn(!1);t++}},1e3)},()=>{clearInterval(yn),yn=void 0,document.title.includes(n.D)||(document.title=n.db),wn(!1)}),c.a.createElement("div",{id:"Main",className:j,onDrop:g,onDragOver:g},c.a.createElement(Le,null),c.a.createElement(Bs,null),c.a.createElement(jn,null),c.a.createElement(gn,{isOpen:i}),c.a.createElement(In,{isOpen:l}),c.a.createElement(fn,{isOpen:b}),c.a.createElement(pn,{isOpen:u}),m&&c.a.createElement(dt,{key:m.id,message:m,noUi:!0}))}));n.o&&console.log(">>> FINISH LOAD MAIN BUNDLE"),Object(s.e)().connectionState||Object(s.d)().initApi()}}]); +//# sourceMappingURL=3.4181bafcca8da716a4b3.js.map \ No newline at end of file diff --git a/dist/3.4181bafcca8da716a4b3.js.map b/dist/3.4181bafcca8da716a4b3.js.map new file mode 100644 index 00000000..ecb1a5a4 --- /dev/null +++ b/dist/3.4181bafcca8da716a4b3.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///./src/modules/actions/ui/chats.ts","webpack:///./src/modules/actions/ui/messages.ts","webpack:///./src/modules/actions/ui/globalSearch.ts","webpack:///./src/modules/actions/ui/localSearch.ts","webpack:///./src/modules/actions/ui/stickerSearch.ts","webpack:///./src/modules/actions/ui/users.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/ui/misc.ts","webpack:///./src/modules/actions/ui/payments.ts","webpack:///./src/modules/actions/api/chats.ts","webpack:///./src/modules/actions/api/messages.ts","webpack:///./src/modules/actions/api/symbols.ts","webpack:///./src/modules/actions/api/globalSearch.ts","webpack:///./src/modules/actions/api/localSearch.ts","webpack:///./src/modules/actions/api/management.ts","webpack:///./src/modules/actions/api/sync.ts","webpack:///./src/modules/actions/api/users.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/api/bots.ts","webpack:///./src/modules/actions/api/twoFaSettings.ts","webpack:///./src/modules/actions/api/payments.ts","webpack:///./src/util/requestQuery.ts","webpack:///./src/modules/actions/apiUpdaters/chats.ts","webpack:///./src/modules/actions/apiUpdaters/messages.ts","webpack:///./src/modules/actions/apiUpdaters/users.ts","webpack:///./src/modules/actions/apiUpdaters/symbols.ts","webpack:///./src/modules/actions/apiUpdaters/misc.ts","webpack:///./src/modules/actions/apiUpdaters/settings.ts","webpack:///./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack:///./src/components/ui/Switcher.tsx","webpack:///./src/components/left/main/LeftMainHeader.tsx","webpack:///./src/components/left/ConnectionState.tsx","webpack:///./src/hooks/useThrottledMemo.ts","webpack:///./src/hooks/useThrottle.ts","webpack:///./src/components/left/main/ChatFolders.tsx","webpack:///./src/components/left/search/LeftSearch.async.tsx","webpack:///./src/components/left/main/ContactList.async.tsx","webpack:///./src/components/left/NewChatButton.tsx","webpack:///./src/components/left/main/LeftMain.tsx","webpack:///./src/components/left/settings/Settings.async.tsx","webpack:///./src/components/left/newChat/NewChat.async.tsx","webpack:///./src/components/left/ArchivedChats.async.tsx","webpack:///./src/components/left/LeftColumn.tsx","webpack:///./src/hooks/useWindowSize.ts","webpack:///./src/hooks/usePrevForAnimation.ts","webpack:///./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack:///./src/hooks/useCurrentOrPrev.ts","webpack:///./src/components/middle/HeaderMenuContainer.async.tsx","webpack:///./src/components/middle/HeaderActions.tsx","webpack:///./src/hooks/useWebpThumbnail.ts","webpack:///./src/components/middle/PinnedMessageNavigation.tsx","webpack:///./src/components/middle/HeaderPinnedMessage.tsx","webpack:///./src/components/middle/AudioPlayer.tsx","webpack:///./src/components/middle/MiddleHeader.tsx","webpack:///./src/components/middle/helpers/groupMessages.ts","webpack:///./src/components/middle/hooks/useStickyDates.ts","webpack:///./src/hooks/useDebounce.ts","webpack:///./src/components/middle/MessageScroll.tsx","webpack:///./src/components/middle/message/helpers/buildContentClassName.ts","webpack:///./src/components/middle/message/helpers/mediaDimensions.ts","webpack:///./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack:///./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack:///./src/components/middle/message/hooks/useFocusMessage.ts","webpack:///./src/components/middle/message/ContextMenuContainer.async.tsx","webpack:///./src/components/middle/ActionMessage.tsx","webpack:///./src/components/common/EmbeddedMessage.tsx","webpack:///./src/components/middle/message/MessageMeta.tsx","webpack:///./src/components/middle/message/Sticker.tsx","webpack:///./src/components/middle/message/hooks/useBlurredMediaThumb.ts","webpack:///./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack:///./src/components/middle/message/Photo.tsx","webpack:///./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack:///./src/components/middle/message/hooks/usePauseOnInactive.ts","webpack:///./src/components/middle/message/Video.tsx","webpack:///./src/components/middle/message/Contact.tsx","webpack:///./src/components/ui/CheckboxGroup.tsx","webpack:///./src/components/middle/message/PollOption.tsx","webpack:///./src/components/middle/message/Poll.tsx","webpack:///./src/components/middle/message/WebPage.tsx","webpack:///./src/components/middle/message/Invoice.tsx","webpack:///./src/components/middle/message/hocs/withSelectControl.tsx","webpack:///./src/components/middle/message/Album.tsx","webpack:///./src/components/middle/message/RoundVideo.tsx","webpack:///./src/components/middle/message/InlineButtons.tsx","webpack:///./src/components/middle/message/CommentButton.tsx","webpack:///./src/components/middle/message/Message.tsx","webpack:///./src/components/middle/MessageList.tsx","webpack:///./src/components/middle/ScrollDownButton.tsx","webpack:///./src/components/middle/composer/helpers/buildAttachment.ts","webpack:///./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack:///./src/util/voiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack:///./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack:///./src/components/middle/composer/hooks/useDraft.ts","webpack:///./src/components/common/DeleteMessageModal.async.tsx","webpack:///./src/components/ui/ResponsiveHoverButton.tsx","webpack:///./src/components/middle/composer/AttachMenu.async.tsx","webpack:///./src/components/middle/composer/SymbolMenu.async.tsx","webpack:///./src/components/middle/composer/MentionMenu.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.async.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.async.tsx","webpack:///./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack:///./src/components/middle/composer/AttachmentModal.async.tsx","webpack:///./src/components/middle/composer/PollModal.async.tsx","webpack:///./src/components/middle/composer/DropArea.async.tsx","webpack:///./src/components/middle/composer/WebPagePreview.tsx","webpack:///./src/components/common/CalendarModal.async.tsx","webpack:///./src/components/payment/PaymentModal.async.tsx","webpack:///./src/components/payment/ReceiptModal.async.tsx","webpack:///./src/components/middle/composer/Composer.tsx","webpack:///./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useEmojiTooltip.ts","webpack:///./src/util/insertHtmlInSelection.ts","webpack:///./src/util/deleteLastCharacterOutsideSelection.ts","webpack:///./src/components/middle/composer/hooks/useEditing.ts","webpack:///./src/components/middle/MobileSearch.async.tsx","webpack:///./src/components/middle/MessageSelectToolbar.async.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.async.tsx","webpack:///./src/components/middle/MiddleColumn.tsx","webpack:///./src/hooks/useCustomBackground.ts","webpack:///./src/components/right/RightHeader.tsx","webpack:///./src/components/right/hooks/useProfileViewportIds.ts","webpack:///./src/components/right/hooks/useProfileState.ts","webpack:///./src/components/right/ProfilePhoto.tsx","webpack:///./src/components/right/ProfileInfo.tsx","webpack:///./src/components/right/hooks/usePhotosPreload.ts","webpack:///./src/components/right/ChatExtra.tsx","webpack:///./src/components/right/Profile.tsx","webpack:///./src/components/right/hooks/useTransitionFixes.ts","webpack:///./src/hooks/useCacheBuster.ts","webpack:///./src/components/right/RightSearch.async.tsx","webpack:///./src/components/right/management/Management.async.tsx","webpack:///./src/components/right/StickerSearch.async.tsx","webpack:///./src/components/right/GifSearch.async.tsx","webpack:///./src/components/right/PollResults.async.tsx","webpack:///./src/components/right/RightColumn.tsx","webpack:///./src/components/mediaViewer/MediaViewer.async.tsx","webpack:///./src/components/main/Notifications.async.tsx","webpack:///./src/components/main/Errors.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["window","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","audioPlayer","selectIsRightColumnShown","pollResults","voters","setTimeout","newGlobal","getGlobal","lastMessageId","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","focusMessage","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","length","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","Static","includes","direction","Down","Up","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","management","byChatId","isActive","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","Object","keys","draftsById","map","Number","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","IS_TOUCH_ENV","loadPinnedMessages","currentUserId","hasUnreadMark","toggleChatUnread","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","requestThreadInfoUpdate","selectSupportChat","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","date","force","isMuted","title","about","photo","memberIds","progress","ChatCreationProgress","InProgress","createdChannel","channelId","accessHash","Complete","Error","createChannel","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","emoticon","orderedIds","maxId","recommendedId","description","newFolder","createChatFolder","Math","max","apply","deleteChatFolder","unreadCount","url","match","RE_TME_INVITE_LINK","exec","RE_TME_LINK","isEnabled","isChatBasicGroup","bannedRights","userId","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","channel","fullChat","isPreHistoryHidden","linkedChatId","offset","uploadProgressCallbacks","Map","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","firstMessageId","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","slice","areSomeLocal","areAllLocal","sendMessage","params","localId","progressCallback","attachment","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","scheduledAt","setReplyingToId","clearWebPagePreview","value","selectReplyingToId","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","v","a","indexOf","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","copyTextToClipboard","link","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","setsById","searchWords","searchStickers","updateStickersForEmoji","loadStickersForEmoji","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","localChats","localUsers","globalChats","globalUsers","userIds","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","contactIds","contactList","updatedUsers","afterSyncCallback","DEBUG","console","log","notifyClientReady","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isChatPrivate","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","draftsByChatId","acc","lastReadInboxMessageId","newCurrentChatId","currentMessageListInfo","threadsById","Array","prototype","concat","replaceUsers","loadAndReplaceMessages","lastSyncTime","sync","afterSync","runDebouncedForFetchFullUser","buildInputPrivacyRules","visibility","allowedIds","deniedIds","usersById","chatsById","rules","collectUsers","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","lastRequestedAt","topPeers","usersHash","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","updateChatMutedState","phone","phoneNumber","updateUser","updateContact","deleteUser","profileId","isPrivate","photos","button","sendBotCommand","command","openTelegramLink","open","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","settings","loadedWallpapers","wallpapers","file","previewBlobUrl","URL","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","document","fileName","size","mimeType","wallpaper","firstWallpaper","withLocalMedia","blocked","blockedIds","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","peerType","isShowPreviews","updateNotifySettings","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isLoading","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","Shipping","PaymentInfo","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","ShippingInfo","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","join","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","Checkout","sendStipeCredentials","shippingOptionId","saveCredentials","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","update","selectIsChatListed","loadTopChats","newProfilePhoto","isNotJoined","listId","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","pick","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","updateWithLocalMedia","isScheduled","currentMessage","video","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","updateScheduledMessage","updateListedAndViewportIds","selectIsViewportNewest","addViewportId","selectThreadByMessage","isMessageLocal","updateChatLastMessage","currentLastMessage","findLastMessage","isDeleting","deleteMessages","newLastMessage","threadIdsToUpdate","unique","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","updateThreadInfo","newMessage","isMessageInCurrentMessageList","isOutgoing","scheduledIds","selectScheduledIds","selectScheduledMessages","deleteChatScheduledMessages","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","poll","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","newResults","targetOption","targetOptionIndex","updatedOption","votersCount","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","key","twoFaSettings","memo","name","label","checked","disabled","inactive","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","theme","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","isNewThemeDark","customBackground","DARK_THEME_BG_COLOR","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","lang","useLang","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_INFO","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","SearchInput","inputId","focused","placeholder","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","transitionRef","activeTab","setActiveTab","useState","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","captureEvents","onSwipe","SwipeDirection","Left","min","Right","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","onSwitchTab","Transition","ref","activeKey","renderCount","LeftSearchAsync","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactListAsync","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","SettingsAsync","NewChatAsync","NewChat","ArchivedChatsAsync","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","captureEscKeyListener","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","removeEventListener","usePrevForAnimation","duration","prev","usePrevious","timeoutRef","isCurrentPresent","calculateMiddleFooterTransforms","windowWidth","canPost","sidePadding","MOBILE_SCREEN_MAX_WIDTH","messageListWidth","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","leftColumnWidth","rightColumnWidth","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","useCurrentOrPrev","shouldSkipUndefined","shouldForceCurrent","HeaderMenuContainerAsync","HeaderMenuContainer","isChatChannel","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canSelect","selectIsInSelectMode","canLeave","joinChannel","openLocalTextSearch","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleSearchClick","querySelector","focus","searchInput","fluid","anchor","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","width","height","radius","count","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","style","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","useFlag","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","senderName","getSenderTitle","noUi","closeAudioPlayer","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioChatId","audioMessageId","audioMessage","originChat","messagesCount","pinnedIds","isSelectModeActive","chatTitleLength","getChatTitle","originChatId","isChatWithBot","selectIsChatWithBot","pinnedMessageIds","firstPinnedMessage","canUnpin","pinnedMessageId","selectForwardedSender","topMessageTitle","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","cycleRestrict","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","newIndex","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","componentEl","add","remove","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","isAlbum","messageOrAlbum","groupMessages","firstUnreadId","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","isFabFrozen","MessageScroll","containerHeight","listItemElementsRef","focusingId","anchorIdRef","anchorTopRef","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","updateFabVisibility","scrollHeight","scrollBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","dataset","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","preservedItemElements","element","teactFastList","data-is-active","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","calculateMediaDimensions","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","AlbumRectPart","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","album","ratios","proportions","ratio","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","REM","getMaxWidth","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","calculateAuthorWidth","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainerAsync","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","senderTitle","MessageMeta","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","Sticker","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","shouldRenderFullMedia","useTransitionForMedia","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumb","fullMediaData","useBlur","LAYERS_TRANSITION_DURATION","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","isPlayAllowed","wasPlaying","isFrozen","freezePlaying","paused","unfreezePlaying","unfreezePlayingOnRaf","hasFocus","useBackgroundMode","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","setIsPlayAllowed","previewMediaData","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","usePauseOnInactive","useVideoCleanup","videoClassName","videoStyle","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","event","newValues","Checkbox","subLabel","getPercentage","toFixed","PollOption","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","floor","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","question","getPollTypeString","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","hasDocument","siteName","displayUrl","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","toString","stopPlaying","requestAnimationFrame","capturePlaying","onRelease","ROUND_VIDEO_DIMENSIONS","poster","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","formatInteger","renderLabel","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","forceSenderName","isAnonymousOwnMessage","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","selectOutgoingStatus","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","shouldAutoLoadMedia","selectShouldAutoLoadMedia","shouldAutoPlayMedia","selectShouldAutoPlayMedia","shouldLoopStickers","selectShouldLoopStickers","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","isLastInList","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","clickInlineButton","bottomMarkerRef","appendixRef","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","avatarPeer","senderPeer","adminTitle","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","showCommentsButton","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","runThrottledOnTickEnd","throttleWithTickEnd","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","getCanPostInChat","selectFirstUnreadId","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","bottomOffset","markMessageListRead","setScrollOffset","scrollOffsetRef","selectScrollOffset","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","normalHeight","String","IS_IOS","webkitOverflowScrolling","clientHeight","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","isAtBottom","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isAlreadyFocusing","isResized","unreadDivider","isAnimatingScroll","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","shouldRenderUnreadDivider","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messsageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","startsWith","preloadImage","newBlob","toBlob","squeezeImage","revokeObjectURL","videoWidth","videoHeight","preloadVideo","createPosterForVideo","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","startedAt","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","volume","subscribeToAnalyzer","stop","reject","onstop","Blob","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","formattedText","currentThreadId","DeleteMessageModalAsync","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenuAsync","AttachMenu","SymbolMenuAsync","SymbolMenu","MentionMenuAsync","MentionMenu","CustomSendMenuAsync","CustomSend","EmojiTooltipAsync","EmojiTooltip","BotKeyboardMenuAsync","BotKeyboardMenu","forwardMessageIds","replyingToId","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModalAsync","AttachmentModal","PollModalAsync","PollModal","DropAreaAsync","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModalAsync","CalendarModal","PaymentModalAsync","PaymentModal","ReceiptModalAsync","MainButtonState","ReceiptModal","chatUser","selectChatUser","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionMenuOpen","mentionFilter","closeMentionMenu","insertMention","mentionFilteredMembers","useMentionMenu","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isEmojiTooltipOpen","closeEmojiTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useEmojiTooltip","canSendStickers","insertTextAndUpdateCursor","selection","getSelection","newHtml","replace","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","execCommand","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","prevChatId","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","tagName","EDITABLE_INPUT_MODAL_ID","items","media","getAsFile","pastedText","getData","substring","preventDefault","useClipboardPaste","handleFileSelect","files","handleClearAttachment","handleSend","currentAttachments","record","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","Portal","containerId","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","onPollCreate","onEmojiSelect","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","selectedAt","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearchAsync","MobileSearch","MessageSelectToolbarAsync","MessageSelectToolbar","UnpinAllMessagesModalAsync","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBackgroundBlurred","isCustomBackgroundColor","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","isMobileSearchActive","loadUser","setDropAreaState","isFabShown","setIsFabShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","renderingThreadId","renderingMessageListType","renderingCanPost","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_ENABLED","messagingDisabledClassName","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleJumpToDate","valueOf","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","isPastMode","submitButtonLabel","useProfileViewportIds","loadMoreMembers","searchMessages","tabType","mediaSearchType","resultType","sortUserIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","currentResultType","handleLoadMore","getMore","useInfiniteScroll","MEMBERS_SLICE","isOnTop","useInfiniteScrollForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","useInfiniteScrollForSharedMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","noProfileInfo","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","isFirstPhoto","isSavedMessages","isDeleted","isDeletedUser","getMediaHash","forceAvatar","getChatAvatarHash","imageHash","ApiMediaFormat","BlobUrl","avatarThumbnailData","useBlurSync","dataUri","imageSrc","prevImageSrc","decoding","userFullName","getUserFullName","getFirstLetters","fullClassName","forceShowSelf","loadFullUser","fullName","slideAnimation","currentPhotoIndex","setCurrentPhotoIndex","isFirst","isLast","profile","currentIndex","usePhotosPreload","handleProfilePhotoClick","ProfileAvatar","selectPreviousMedia","selectNextMedia","excludedClosestSelector","renderPhoto","isVerifiedIconShown","isVerified","renderPhotoTabs","aria-label","VerifiedIcon","isUserOnline","getUserStatus","canInviteUsers","isUserRightBanned","getHasAdminRight","currentIsMuted","chatUsername","entity","handleNotificationChange","formattedNumber","getChatDescription","getChatLink","printedUsername","printedDescription","ListItem","multiline","narrow","TABS","buildInfiniteScrollItemSelector","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","loadProfilePhotos","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","RightSearchAsync","RightSearch","ManagementAsync","Management","StickerSearchAsync","GifSearchAsync","PollResultsAsync","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","NotificationsAsync","ErrorsAsync","Errors","ForwardPickerAsync","ForwardPicker","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","initialUnread","selectCountNotMutedUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","onDrop","onDragOver","initAp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xC,GAAI1jE,SAASnY,MAAMnK,SAASimF,KAC1Bf,IAAW,OADb,CAKA,GAAIl0E,EAAQ,GAAM,EAAG,CACnB,MAAMk1E,EAAYJ,YAA0BnnF,eAAeknF,EACvDK,EAAY,IACd5jE,SAASnY,MAAS,GAAE+7E,iBAAyBA,EAAY,EAAI,IAAM,KACnEhB,IAAW,SAGb5iE,SAASnY,MAAQg8E,KACjBjB,IAAW,GAGbl0E,MA5FwB,MA8FzB,KACD+0E,cAAcf,IACdA,QAAuBtoF,EAElB4lB,SAASnY,MAAMnK,SAASimF,OAC3B3jE,SAASnY,MAAQg8E,MAGnBjB,IAAW,KASX,yBAAKxpF,GAAG,OAAO6zB,UAAWA,EAAW62D,OAAQR,EAAWS,WAAYT,GAClE,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,CAAap0D,OAAQ4zD,IACrB,kBAAC,GAAD,CAAe5zD,OAAQ8zD,IACvB,kBAAC,GAAD,CAAe9zD,OAAQg0D,IACvB,kBAAC,GAAD,CAAQh0D,OAAQi0D,IACfj8C,GAAgB,kBAAC,GAAD,CAAa9a,IAAK8a,EAAa9tC,GAAI8I,QAASglC,EAAcnB,MAAI,QClKjF7rB,KAEFC,QAAQC,IAAI,+BAGT/d,cAAY81B,iBACf34B,cAAcwqF","file":"3.4181bafcca8da716a4b3.js","sourcesContent":["import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\n\nconst FOCUS_DURATION = 2000;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {},\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && ids.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n return toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n});\n\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings } from '../../../types';\nimport { replaceSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n const { id } = payload!;\n\n return {\n ...global,\n isLeftColumnShown: id === undefined,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: 0,\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global) => {\n const newNotifications = [...global.notifications];\n\n newNotifications.pop();\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showError', (global, actions, payload) => {\n const { error } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if (!getReadableErrorText(error)) {\n return global;\n }\n\n const newErrors = [...global.errors];\n const existingErrorIndex = newErrors.findIndex((err) => err.message === error.message);\n if (existingErrorIndex !== -1) {\n newErrors.splice(existingErrorIndex, 1);\n }\n\n newErrors.push(error);\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('dismissError', (global) => {\n const newErrors = [...global.errors];\n\n newErrors.pop();\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\nimport {\n clearPayment, closeInvoice,\n} from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n RE_TME_INVITE_LINK,\n RE_TME_LINK,\n TIPS_USERNAME,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n} from '../../reducers';\nimport {\n selectChat,\n selectCurrentChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\n\nconst TOP_CHATS_PRELOAD_PAUSE = 200;\n// We expect this ID does not exist\nconst TMP_CHAT_ID = -1;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), 1000, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForLoadFullChat = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: number[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHATS_PRELOAD_PAUSE);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n\n if (IS_TOUCH_ENV) {\n actions.loadPinnedMessages({ chatId: chatToPreload.id });\n }\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat && chat.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n\n actions.openChat({ id: chat ? chat.id : TMP_CHAT_ID });\n\n if (chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions) => {\n actions.openChatByUsername({ username: TIPS_USERNAME });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', chat);\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('updateChatMutedState', { chat, isMuted });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('leaveChannel', { channelId, accessHash });\n }\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('deleteChannel', { channelId, accessHash });\n }\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n let match = RE_TME_INVITE_LINK.exec(url);\n\n if (match) {\n const hash = match[1];\n\n (async () => {\n const chat = await callApi('openChatByInvite', hash);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n })();\n } else {\n match = RE_TME_LINK.exec(url)!;\n\n const username = match[1];\n const channelPostId = match[2] ? Number(match[2]) : undefined;\n\n void openChatByUsername(actions, username, channelPostId);\n }\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n void openChatByUsername(actions, username);\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById).map(Number),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo && channel.fullInfo.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: number, offsetDate?: number) {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: getGlobal().chats.orderedPinnedIds[listType] === undefined,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChat = await callApi('createGroupChat', { title, users });\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: chatId });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', { chatId, photo });\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n if (channelPostId) {\n actions.focusMessage({ chatId: localChat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: localChat.id });\n }\n return;\n }\n\n const previousChat = selectCurrentChat(global);\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n if (previousChat) {\n actions.openChat({ id: previousChat.id });\n }\n\n actions.showNotification({ message: 'User does not exist' });\n\n return;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE } from '../../../config';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport { areSortedArraysIntersecting, buildCollectionByKey, split } from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n} from '../../selectors';\nimport { rafPromise } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map();\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const { chatId, messageId, replyOriginForId } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void loadMessage(chat, messageId, replyOriginForId);\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', draft);\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n const { chatId, maxId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n const { maxId } = payload!;\n\n void callApi('markMessageListRead', { chat, threadId, maxId });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter(Boolean as any)\n : undefined;\n\n if (fromChat && toChat && messages && messages.length) {\n void forwardMessages(fromChat, toChat, messages);\n }\n});\n\naddReducer('loadScheduledHistory', (global) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { hash } = global.scheduledMessages.byChatId[chat.id] || {};\n\n void loadScheduledHistory(chat, hash);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos, firstMessageId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\n chat: ApiChat;\n text: string;\n entities: ApiMessageEntity[];\n replyingTo: number;\n attachment: ApiAttachment;\n sticker: ApiSticker;\n gif: ApiVideo;\n poll: ApiNewPoll;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo) {\n await rafPromise();\n }\n\n const global = getGlobal();\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nfunction forwardMessages(\n fromChat: ApiChat,\n toChat: ApiChat,\n messages: ApiMessage[],\n) {\n callApi('forwardMessages', {\n fromChat,\n toChat,\n messages,\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n const isUnique = (v: number, i: number, a: number[]) => a.indexOf(v) === i;\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: [\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ].filter(isUnique),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadMessageLink', (global, actions, payload) => {\n const { messageId, chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchMessageLink', { chat, message });\n\n if (result) {\n copyTextToClipboard(result.link);\n }\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat, historyHash?: number) {\n const result = await callApi('fetchScheduledHistory', { chat, hash: historyHash });\n if (!result) {\n return;\n }\n\n const { hash, messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId, hash);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\nasync function loadStickerSets(hash = 0) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash = 0) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash = 0) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash = 0) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string) {\n const stickerSet = await callApi('fetchStickers', { stickerSetId, accessHash });\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\nasync function searchStickers(query: string, hash = 0) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash = 0) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash = 0) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {};\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalUsers.map(({ id }) => id),\n userIds: globalChats.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results ? results.nextOffsetId : undefined;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo ? threadInfo.topMessageId : undefined;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults ? currentResults.nextOffsetId : undefined;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { notifyClientReady } from '../../../util/pushNotifications';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n} from '../../reducers';\nimport {\n selectUser, selectChat, selectCurrentMessageList, selectDraft,\n} from '../../selectors';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n });\n if (!result) {\n return undefined;\n }\n\n let global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isChatPrivate(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n });\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n return draft ? { ...acc, [chatId]: draft } : acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const byId = buildCollectionByKey(result.messages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n [currentChatId]: {\n byId,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]),\n listedIds,\n viewportIds: listedIds,\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).map(Number).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, updateManagementProgress, updateUser, updateUsers,\n} from '../../reducers';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60000; // 1 min\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { hash, lastRequestedAt } = global.topPeers;\n\n if (!lastRequestedAt || Date.now() - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers(hash);\n }\n});\n\naddReducer('loadContactList', (global) => {\n const { hash } = global.contactList || {};\n void loadContactList(hash);\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers(usersHash?: number) {\n const result = await callApi('fetchTopUsers', { hash: usersHash });\n if (!result) {\n return;\n }\n\n const { hash, ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n hash,\n userIds: ids,\n lastRequestedAt: Date.now(),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList(hash?: number) {\n const contactList = await callApi('fetchContactList', { hash });\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n hash: contactList.hash,\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: number,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n const result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: number) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteUser', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isChatPrivate(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationsSettings', () => {\n (async () => {\n const result = await callApi('loadNotificationsSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, isShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, isShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, isShowPreviews));\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: number) => {\n if (isChatPrivate(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n","import { addReducer, getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { RE_TME_INVITE_LINK, RE_TME_LINK } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChatMessage, selectCurrentChat } from '../../selectors';\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_INVITE_LINK) || button.value.match(RE_TME_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n window.open(button.value);\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n if (!currentUserId || !chat) {\n return;\n }\n\n void sendBotCommand(chat, currentUserId, command);\n});\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: number, command: string) {\n await callApi('sendMessage', {\n chat,\n text: command,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result || !result.message) {\n return;\n }\n\n const { message, alert: isError } = result;\n\n if (isError) {\n getDispatch().showError({ error: { message } });\n } else {\n getDispatch().showNotification({ message });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types/index';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n} from '../../selectors';\n\nimport { getStripeError } from '../../helpers/payments';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const messageId = selectPaymentMessageId(global);\n if (!messageId) {\n return;\n }\n validateRequestedInfo(messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', { messageId, requestInfo, shouldSave });\n if (!result) {\n return;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { messageId } = payload;\n if (!messageId) {\n return;\n }\n getPaymentForm(messageId);\n});\n\n\nasync function getPaymentForm(messageId: number) {\n const result = await callApi('getPaymentForm', { messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n if (!messageId || !receiptMessageId || !chatId) {\n return;\n }\n getReceipt(messageId, receiptMessageId, chatId);\n});\n\nasync function getReceipt(messageId: number, receiptMessageId: number, chatId: number) {\n const result = await callApi('getReceipt', receiptMessageId);\n if (!result) {\n return;\n }\n let global = getGlobal();\n const message = selectChatMessage(global, chatId, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n sendStipeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const messageId = selectPaymentMessageId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!messageId || !publishableKey) {\n return;\n }\n sendPaymentForm(messageId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStipeCredentials(data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n},\npublishableKey: string) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n messageId: number,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n messageId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n} from '../../selectors';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1000;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n setGlobal(updateChat(global, update.id, update.chat, update.newProfilePhoto));\n\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== update.id));\n }\n\n global = updateChat(global, update.id, { isNotJoined: true });\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n if (update.chatId === currentChatId) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id);\n const chat = selectChat(global, chatId);\n if (chat && chat.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo && targetChat.fullInfo.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat && chat.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { getMessageContent, isChatPrivate, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const { chatId, id, message } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content && message.content.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!message.isOutgoing) {\n setTimeout(() => {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds]\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const { chatId, threadId, threadInfo } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isChatPrivate(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const ids = Object.keys(global.messages.byChatId[chatId].byId).map(Number);\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message && message.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: number, id: number, message: Partial, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, message: ApiMessage) {\n const { id, chatId } = message;\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n global = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n }\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!firstMessageId && isMessageLocal(message)) {\n return global;\n }\n\n if (threadInfo) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n\n if (!threadInfo.lastMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n });\n }\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: number,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId] && chats.byId[chatId].lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: number) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, updateUser } from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: [number, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: number, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n hash: 0,\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.isShowPreviews);\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Switcher.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n checked?: boolean;\n disabled?: boolean;\n inactive?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC = ({\n id,\n name,\n value,\n label,\n checked = false,\n disabled,\n inactive,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((e: ChangeEvent) => {\n if (onChange) {\n onChange(e);\n }\n\n if (onCheck) {\n onCheck(e.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n inactive && 'inactive',\n );\n\n return (\n \n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n APP_INFO, DEFAULT_PATTERN_COLOR, FEEDBACK_URL, DARK_THEME_BG_COLOR, DARK_THEME_PATTERN_COLOR,\n} from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n onReset()}\n ariaLabel={hasMenu ? 'Open menu' : 'Return to chat list'}\n >\n
\n \n );\n }, [hasMenu, onReset]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n const isNewThemeDark = newTheme === 'dark';\n\n setSettingOption({\n theme: newTheme,\n customBackground: isNewThemeDark ? DARK_THEME_BG_COLOR : undefined,\n patternColor: isNewThemeDark ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n switchTheme(newTheme, animationLevel > 0);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const lang = useLang();\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n
\n
\n \n \n {lang('SavedMessages')}\n \n \n {lang('ArchivedChats')}\n {archivedUnreadChatsCount > 0 && (\n
{archivedUnreadChatsCount}
\n )}\n \n \n {lang('Contacts')}\n \n \n {lang('Settings')}\n \n \n Dark Mode\n \n \n \n {lang('Appearance.Animations').toLowerCase()}\n 0}\n />\n \n \n Telegram Features\n \n \n Report Bug\n \n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { theme, animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { FC } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = ({ connectionState }) => {\n const lang = useLang();\n\n const isConnecting = connectionState === 'connectionStateConnecting';\n\n return isConnecting && (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef();\n const runThrottled = useThrottle(ms);\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n let isSync = true;\n runThrottled(() => {\n valueRef.current = resolverFn();\n\n if (!isSync) {\n forceUpdate();\n }\n });\n isSync = false;\n }, dependencies);\n\n return valueRef.current;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms);\n }, [ms]);\n};\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n orderedFolderIds?: number[];\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst INFO_THROTTLE = 3000;\n\nconst ChatFolders: FC = ({\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n loadChatFolders,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: 'All' },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveTab(index);\n }, []);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeTab >= folderTabs.length) {\n setActiveTab(0);\n }\n }, [activeTab, folderTabs]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, folderTabs]);\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n const lang = useLang();\n\n function renderCurrentTab() {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ title }) => title === folderTabs![activeTab].title);\n\n if (!activeFolder || activeTab === 0) {\n return ;\n }\n\n return ;\n }\n\n return (\n
\n {folderTabs && folderTabs.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n },\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadChatFolders']),\n)(ChatFolders));\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? : ;\n};\n\nexport default LeftSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? : ;\n};\n\nexport default ContactListAsync;\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n New Private Chat\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, memo, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = {};\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\n onReset,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n return (\n \n \n \n \n {() => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n \n
\n );\n};\n\nexport default memo(LeftMain);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? : ;\n};\n\nexport default SettingsAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? : ;\n};\n\nexport default NewChatAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? : ;\n};\n\nexport default ArchivedChatsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n};\n\ntype DispatchProps = Pick;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC = ({\n searchQuery,\n searchDate,\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n}) => {\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n default:\n break;\n }\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [content, setGlobalSearchQuery, setGlobalSearchChatId, setGlobalSearchDate, resetChatCreation, settingsScreen]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList ? captureEscKeyListener(() => handleReset()) : undefined),\n [content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n return (\n \n {() => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n \n );\n case ContentType.Settings:\n return (\n \n );\n case ContentType.NewChannel:\n return (\n \n );\n case ContentType.NewGroup:\n return (\n \n );\n default:\n return (\n \n );\n }\n }}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { query, date } = global.globalSearch;\n return { searchQuery: query, searchDate: date };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError',\n ]),\n)(LeftColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { IDimensions } from '../modules/helpers';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\n\nconst RESIZE_TIMEOUT_MS = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, RESIZE_TIMEOUT_MS, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n });\n\n return size;\n};\n","import { useRef } from '../lib/teact/teact';\n\nimport usePrevious from './usePrevious';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport default function usePrevForAnimation(current: any, duration?: number) {\n const prev = usePrevious(current, true);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n // eslint-disable-next-line no-null/no-null\n const isCurrentPresent = current !== undefined && current !== null;\n\n if (isCurrentPresent && timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useOnChange(() => {\n // When `current` becomes empty\n if (duration && !isCurrentPresent && prev && !timeoutRef.current) {\n timeoutRef.current = window.setTimeout(() => {\n timeoutRef.current = undefined;\n forceUpdate();\n }, duration);\n }\n }, [current]);\n\n return isCurrentPresent || (duration && !timeoutRef.current) ? current : prev;\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import usePrevious from './usePrevious';\n\nexport default function useCurrentOrPrev(\n current: T, shouldSkipUndefined = false, shouldForceCurrent = false,\n): T | undefined {\n const prev = usePrevious(current, shouldSkipUndefined);\n\n // eslint-disable-next-line no-null/no-null\n return shouldForceCurrent || (current !== null && current !== undefined) ? current : prev;\n}\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default HeaderMenuContainerAsync;\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectIsChatBotNotStarted, selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick;\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n isRightColumnShown,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_MOBILE_SCREEN) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n const lang = useLang();\n\n return (\n
\n {!IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {!IS_MOBILE_SCREEN && canStartBot && (\n \n {lang('Start')}\n \n )}\n {!IS_MOBILE_SCREEN && canSearch && (\n \n \n \n )}\n {(IS_MOBILE_SCREEN || !canSubscribe) && (\n \n \n \n )}\n {menuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (chat && chat.isRestricted) {\n return {\n noMenu: true,\n };\n }\n\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canStartBot = Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canSelect = !selectIsInSelectMode(global);\n const canLeave = isMainThread && !canSubscribe;\n\n const noMenu = !(\n (IS_MOBILE_SCREEN && canSubscribe)\n || (IS_MOBILE_SCREEN && canSearch)\n || canMute\n || canSelect\n || canLeave\n );\n\n return {\n noMenu,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbnail = message && getMessageMediaThumbDataUri(message);\n const { sticker } = (message && message.content) || {};\n const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message && message.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbnail!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbnail]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbnail;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef && containerRef.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n
\n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n const lang = useLang();\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiAudio, ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageAudio, getMessageKey, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n senderName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst AudioPlayer: FC = ({\n message, className, noUi, senderName, focusMessage, closeAudioPlayer,\n}) => {\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const { playPause, isPlaying } = useAudioPlayer(\n getMessageKey(message), getMediaDuration(message)!, mediaData, undefined, undefined, true,\n );\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n }, [closeAudioPlayer, isPlaying, playPause]);\n\n const lang = useLang();\n\n if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n
\n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n \n
\n\n \n \n \n
\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n
{renderText(title || fileName)}
\n {performer && (\n
{renderText(performer)}
\n )}\n \n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n
{senderName && renderText(senderName)}
\n
{subtitle}
\n \n );\n}\n\nexport default withGlobal(\n (global, { message }) => {\n const sender = selectSender(global, message);\n const senderName = sender ? getSenderTitle(sender) : undefined;\n\n return { senderName };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage', 'closeAudioPlayer']),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiTypingStatus,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n isChatPrivate,\n isChatArchived,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadOriginChat,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n};\n\ntype StateProps = {\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageTitle?: string;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatTitleLength?: number;\n chatsById?: Record;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageTitle,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chatTitleLength,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds) ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : 0);\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\n\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [chatId]);\n\n // Modify index after unpinning\n useEffect(() => {\n setPinnedMessageIndex(pinnedMessagesCount ? cycleRestrict(pinnedMessagesCount, pinnedMessageIndex) : -1);\n }, [pinnedMessagesCount, pinnedMessageIndex]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = windowWidth >= MOBILE_SCREEN_MAX_WIDTH && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef(null);\n const shouldAnimateTools = useRef(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const handleBackClick = useCallback(() => {\n if (IS_MOBILE_SCREEN) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread') {\n if (IS_MOBILE_SCREEN) {\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n let isActive = false;\n\n const totalCount = Object.values(chatsById).reduce((total, chat) => {\n if (isChatArchived(chat)) {\n return total;\n }\n\n const count = chat.unreadCount || 0;\n if (count && (!chat.isMuted || chat.unreadMentionsCount)) {\n isActive = true;\n }\n\n return total + count;\n }, 0);\n\n if (!totalCount) {\n return undefined;\n }\n\n return {\n isActive,\n totalCount,\n };\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(pinnedMessage && !shouldRenderAudioPlayer);\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const lang = useLang();\n\n function renderInfo() {\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

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

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

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

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

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

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n
\n {isChatPrivate(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n
\n \n
\n \n {unreadCountInfo && (\n
\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n
\n )}\n
\n );\n }\n\n return (\n
\n \n {renderInfo}\n \n\n
\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n \n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n const originChat = selectThreadOriginChat(global, chatId, threadId);\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds && pinnedIds.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds && scheduledIds.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (threadInfo) {\n messagesCount = threadInfo.messagesCount;\n }\n }\n\n let state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chatTitleLength: chat && getChatTitle(chat).length,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType === 'thread' && messagesById) {\n if (threadId === MAIN_THREAD_ID) {\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n\n if (pinnedMessageIds && pinnedMessageIds.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n state = {\n ...state,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n };\n }\n } else {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const sender = message ? selectForwardedSender(global, message) : undefined;\n const topMessageTitle = sender ? getSenderTitle(sender) : undefined;\n\n state = {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n messagesById,\n canUnpin: false,\n topMessageTitle,\n };\n }\n }\n\n return state;\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDatetime = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDatetime) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDatetime,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebounce(ms: number, shouldRunFirst?: boolean, shouldRunLast?: boolean) {\n return useMemo(() => {\n return debounce((cb) => cb(), ms, shouldRunFirst, shouldRunLast);\n }, [ms, shouldRunFirst, shouldRunLast]);\n}\n","import { MutableRefObject } from 'react';\nimport React, {\n FC, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { MESSAGE_LIST_SENSITIVE_AREA } from '../../config';\nimport resetScroll from '../../util/resetScroll';\nimport { useIntersectionObserver, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\n\ntype OwnProps = {\n containerRef: MutableRefObject;\n className: string;\n messageIds: number[];\n containerHeight?: number;\n listItemElementsRef: MutableRefObject;\n anchorIdRef: MutableRefObject;\n anchorTopRef: MutableRefObject;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n focusingId?: number;\n onFabToggle: AnyToVoidFunction;\n children: any;\n};\n\nconst FAB_THRESHOLD = 50;\nconst FAB_FREEZE_TIMEOUT = 100;\n\n// Local flag is used because `freeze/unfreeze` methods are controlled by heavy animation\nlet isFabFrozen = false;\n\nconst MessageScroll: FC = ({\n containerRef,\n className,\n messageIds,\n containerHeight,\n listItemElementsRef,\n focusingId,\n anchorIdRef,\n anchorTopRef,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n children,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef(null);\n\n const updateFabVisibility = useCallback(() => {\n if (isFabFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = scrollHeight - scrollTop - offsetHeight;\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom === 0;\n\n onFabToggle(firstUnreadId ? !isAtBottom : !isNearBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId]);\n\n const {\n observe: observeIntersection,\n freeze: freezeForLoadMore,\n unfreeze: unfreezeForLoadMore,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger' && (target as HTMLDivElement).dataset.isActive) {\n resetScroll(containerRef.current!);\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD,\n }, ([{ target }]) => {\n if ((target as HTMLDivElement).dataset.isActive) {\n updateFabVisibility();\n }\n });\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n // Do not load more and show FAB when focusing\n useOnChange(() => {\n if (focusingId) {\n freezeForLoadMore();\n freezeForFab();\n } else {\n unfreezeForFab();\n unfreezeForLoadMore();\n }\n }, [focusingId]);\n\n // Remember scroll position before updating height\n useOnChange(() => {\n if (!listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n }, [messageIds, containerHeight]);\n\n // Workaround for FAB flickering with tall incoming message\n useOnChange(() => {\n isFabFrozen = true;\n\n setTimeout(() => {\n isFabFrozen = false;\n }, FAB_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n // Workaround for stuck FAB when many unread messages\n useEffect(updateFabVisibility, [firstUnreadId]);\n\n return (\n
\n
\n {children}\n \n \n
\n );\n};\n\nexport default MessageScroll;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMediaWithNoText = (photo || video) && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video && video.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean) {\n return hasText ? MIN_MEDIA_WIDTH_WITH_TEXT : MIN_MEDIA_WIDTH;\n}\n\nexport function calculateMediaDimensions(message: ApiMessage) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto)\n : calculateVideoDimensions(video!, isOwn, isForwarded);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage } from '../../../../api/types';\nimport { IDimensions } from '../../../../modules/helpers';\n\nimport { MOBILE_SCREEN_MAX_WIDTH } from '../../../../config';\nimport { REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nconst MAX_WIDTH_MOBILE_VW = 69;\nconst MAX_WIDTH_DESK_OWN_REM = 30;\nconst MAX_WIDTH_DESK_REM = 29;\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: IDimensions;\n};\n\nfunction getMaxWidth(isOwn: boolean, isForwarded: boolean, windowWidth: number) {\n if (windowWidth <= MOBILE_SCREEN_MAX_WIDTH) {\n return (windowWidth / 100) * MAX_WIDTH_MOBILE_VW - (isForwarded ? 1.625 : 0) * REM;\n }\n\n const maxWidth = isOwn ? MAX_WIDTH_DESK_OWN_REM : MAX_WIDTH_DESK_REM;\n\n return (maxWidth - (isForwarded ? 1.625 : 0)) * REM;\n}\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as IDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: IDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n album: IAlbum,\n windowWidth: number,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getMaxWidth(isOwn, isForwarded, windowWidth);\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","let element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n element.style.font = '400 12px Roboto, \"Helvetica Neue\", \"Apple Color Emoji\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\nimport { FocusDirection } from '../../../../types';\n\n// This is the max scroll offset within existing viewport.\nconst FOCUS_MAX_OFFSET = 1500;\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: number,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'center',\n FOCUS_MARGIN,\n focusDirection === undefined ? FOCUS_MAX_OFFSET : RELOCATED_FOCUS_OFFSET,\n focusDirection,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? : undefined;\n};\n\nexport default ContextMenuContainerAsync;\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n targetUser?: ApiUser;\n targetMessage?: ApiMessage;\n targetChatId?: number;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const content = renderActionMessageText(\n message,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const userId = message.senderId;\n const { targetUserId, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n sender,\n ...(targetUserId && { targetUser: selectUser(global, targetUserId) }),\n targetChatId,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n\n useLang();\n\n const senderTitle = sender && getSenderTitle(sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl)}\n
\n
{renderText(senderTitle || title || NBSP)}
\n

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

\n
\n
\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: () => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default MessageMeta;\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(isMediaReady, 'slow');\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && shouldRenderFullMedia && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { LAYERS_TRANSITION_DURATION } from '../../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useBlur from '../../../../hooks/useBlur';\n\nexport default function useBlurredMediaThumb(message: ApiMessage, fullMediaData?: string) {\n return useBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN ? LAYERS_TRANSITION_DURATION : undefined,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = 'rgba(255,255,255,1)';\n\nexport default async (src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean) => {\n return isSelected ? SELECTED_APPENDIX_BACKGROUND : getAppendixColorFromImage(src, isOwn);\n};\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n shouldAffectAppendix,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = isDownloadAllowed && isIntersecting;\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, size), !shouldDownload);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbDataUri = useBlurredMediaThumb(message, fullMediaData);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, shouldDownload && !fullMediaData);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled, 'slow');\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(fullMediaData, 'slow');\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const thumbClassName = buildClassName(\n 'thumbnail',\n !thumbDataUri && 'empty',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!fullMediaData && !isDownloadAllowed && (\n \n )}\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport safePlay from '../../../../util/safePlay';\n\nexport default (playerRef: { current: HTMLVideoElement | null }, isPlayAllowed = false) => {\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const freezePlaying = useCallback(() => {\n isFrozen.current = true;\n\n if (!isPlayAllowed || !playerRef.current) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = !playerRef.current.paused;\n }\n\n playerRef.current.pause();\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n // At this point HTMLVideoElement can be unmounted from the DOM\n if (isPlayAllowed && playerRef.current && wasPlaying.current && document.body.contains(playerRef.current)) {\n safePlay(playerRef.current);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n if (!document.hasFocus()) {\n freezePlaying();\n }\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n};\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n canMessagePlayVideoInline,\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n\n const video = message.content.video!;\n const localBlobUrl = video.blobUrl;\n const canPlayInline = Boolean(localBlobUrl) || canMessagePlayVideoInline(video);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(shouldAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, previewBlobUrl);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const previewMediaData = previewBlobUrl || thumbDataUri;\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(canPlayInline && isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && (canPlayInline && !isBuffered),\n );\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(fullMediaData, 'slow');\n\n const [playProgress, setPlayProgress] = useState(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded);\n\n useHeavyAnimationCheckForVideo(videoRef, Boolean(isInline && shouldAutoPlay));\n\n usePauseOnInactive(videoRef, isPlayAllowed);\n\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (canPlayInline && !fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (canPlayInline && fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, canPlayInline, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const thumbClassName = buildClassName('thumbnail', !previewMediaData && 'empty');\n const videoClassName = buildClassName('full-media', transitionClassNames);\n const videoStyle = previewMediaData ? `background-image: url(${previewMediaData}); background-size: cover` : '';\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n const shouldRenderInlineVideo = isInline;\n const shouldRenderHqPreview = !canPlayInline && mediaData;\n const shouldRenderPlayButton = !canPlayInline || (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = canPlayInline && !isDownloadAllowed;\n\n return (\n \n {(shouldRenderThumb || !isInline) && (\n \n )}\n {shouldRenderInlineVideo && (\n \n \n \n )}\n {shouldRenderHqPreview && (\n \n )}\n {shouldRenderPlayButton && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && (\n \n )}\n {isTransferring && !canPlayInline ? (\n {Math.round(transferProgress * 100)}%\n ) : isTransferring && canPlayInline ? (\n ...\n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(video.duration - playProgress)}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst Contact: FC = ({\n contact, user, openUserInfo,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n return {\n user: selectUser(global, contact.userId),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, memo, useState,\n} from '../../lib/teact/teact';\n\nimport Checkbox from './Checkbox';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n};\n\ntype OwnProps = {\n id?: string;\n options: IRadioOption[];\n selected?: string[];\n disabled?: boolean;\n round?: boolean;\n loadingOptions?: string[];\n onChange: (value: string[]) => void;\n};\n\nconst CheckboxGroup: FC = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState([]);\n\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value, checked } = event.currentTarget;\n let newValues: string[];\n if (checked) {\n newValues = [...values, value];\n } else {\n newValues = values.filter((v) => v !== value);\n }\n\n setValues(newValues);\n onChange(newValues);\n }, [onChange, values]);\n\n return (\n
\n {options.map((option) => (\n \n ))}\n
\n );\n};\n\nexport default memo(CheckboxGroup);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result && result.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n \n \n `;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n
\n
\n {answerPercent}%\n {showIcon && (\n \n \n \n )}\n
\n
\n
\n {renderText(answer.text)}\n
\n
\n
\n \n
\n
\n
\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n loadMessage,\n onSendVote,\n openPollResults,\n}) => {\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [chosenOptions, setChosenOptions] = useState([]);\n const [isSolutionShown, setIsSolutionShown] = useState(false);\n const [wasSubmitted, setWasSubmitted] = useState(false);\n const [closePeriod, setClosePeriod] = useState(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000), summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${formatMediaDuration(closePeriod)}\n \n \n `;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n \n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n
\n {recentVoters.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n \n )\n );\n }\n\n return (\n
\n {renderSolution()}\n
{renderText(summary.question)}
\n
\n {getPollTypeString(summary)}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote &&
}\n {summary.quiz && poll.results.solution && !canVote && (\n \n \n \n )}\n
\n {canVote && (\n
\n {isMultiple\n ? (\n \n )\n : (\n \n )}\n
\n )}\n {!canVote && (\n
\n {summary.answers.map(renderResultOption)}\n
\n )}\n {!canViewResult && !isMultiple && (\n
{getReadableVotersCount(summary.quiz, results.totalVoters)}
\n )}\n {isMultiple && (\n \n {lang('PollSubmitVotes')}\n \n )}\n {canViewResult && (\n \n {lang('PollViewResults')}\n \n )}\n
\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'Quiz' : 'Anonymous Quiz';\n }\n\n if (summary.closed) {\n return 'Final results';\n }\n\n return summary.isPublic ? 'Poll' : 'Anonymous Poll';\n}\n\nfunction getReadableVotersCount(isQuiz: true | undefined, count?: number) {\n if (!count) {\n return isQuiz ? 'No answers yet' : 'No voters yet';\n }\n\n return isQuiz ? `${count} answered` : `${count} voted`;\n}\n\nexport default memo(withGlobal(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { byId: usersById } = global.users;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n inPreview?: boolean;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n inPreview,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n if (webPage && (isSquarePhoto || webPage.hasDocument)) {\n window.open(webPage.url);\n } else if (onMediaClick) {\n onMediaClick();\n }\n }, [webPage, isSquarePhoto, onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = webPage;\n\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n );\n\n return (\n \n {photo && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

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

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

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

{renderText(title)}

\n )}\n {text && (\n

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

\n )}\n
\n {photoUrl && (\n \n )}\n {description && (\n

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

\n )}\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nexport default function withSelectControl(WrapedComponent: FC) {\n const Component: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(Component));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n};\n\ntype DispatchProps = Pick;\n\nconst Album: FC = ({\n album,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n cancelSendingMessage,\n}) => {\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload ? fileUpload.progress : undefined;\n const { dimensions, sides } = albumLayout.layout[index];\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom)\n );\n\n return (\n \n );\n } else if (video) {\n return (\n \n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n \n {album.messages.map(renderAlbumMessage)}\n \n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n return {\n uploadsById: global.fileUploads.byMessageLocalId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport buildClassName from '../../../util/buildClassName';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport safePlay from '../../../util/safePlay';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n lastSyncTime?: number;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad && shouldAutoPlay);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = isDownloadAllowed && !isBuffered;\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n const [isActivated, setIsActivated] = useState(false);\n const [progress, setProgress] = useState(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const circumference = 94 * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `\n \n `;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n requestAnimationFrame(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n\n usePauseOnInactive(playerRef, Boolean(mediaData));\n\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n } else {\n playerEl.pause();\n }\n } else {\n playerEl.currentTime = 0;\n setIsActivated(true);\n capturePlaying();\n }\n }, [capturePlaying, isActivated, mediaData]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n \n {shouldRenderThumb && (\n
\n \n
\n )}\n {mediaData && (\n
\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n \n \n
\n )}\n
\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {!mediaData && !isDownloadAllowed && (\n \n )}\n
\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && }\n
\n
\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC = ({ message, onClick }) => {\n return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {button.text}\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../../modules/helpers';\nimport { formatInteger, formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst CommentButton: FC = ({\n disabled, threadInfo, usersById, chatsById, openChat,\n}) => {\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isChatPrivate(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n
\n {recentRepliers.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n \n \n {(!recentRepliers || recentRepliers.length === 0) && }\n {renderRecentRepliers()}\n
{renderLabel(messagesCount)}
\n \n \n );\n};\n\nfunction renderLabel(messagesCount: number) {\n if (messagesCount === 0) {\n return 'Leave a Comment';\n }\n\n if (messagesCount === 1) {\n return '1 Comment';\n }\n\n return `${formatInteger(messagesCount)} Comments`;\n}\n\nexport default memo(withGlobal(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { FocusDirection, IAlbum, MediaViewerOrigin } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectShouldAutoLoadMedia,\n selectShouldAutoPlayMedia, selectShouldLoopStickers,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji, getSenderTitle, getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentsButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n forceSenderName?: boolean;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isChannel?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n shouldAutoLoadMedia?: boolean;\n shouldAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '';\nconst APPEARANCE_DELAY = 10;\n\nconst Message: FC = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n shouldAutoLoadMedia,\n shouldAutoPlayMedia,\n shouldLoopStickers,\n focusMessage,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n openChat,\n cancelSendingMessage,\n markMessagesRead,\n sendPollVote,\n toggleMessageSelection,\n setReplyingToId,\n openForwardMenu,\n clickInlineButton,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const { width: windowWidth } = useWindowSize();\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { chatId, id: messageId, threadInfo } = message;\n\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const { forwardInfo, viaBotId } = message;\n const asForwarded = forwardInfo && !isChatWithSelf && !forwardInfo.isLinkedChannelPost;\n const isInDocumentGroup = !!message.groupedId && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n });\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n\n useEnsureMessage(chatId, hasReply ? message.replyToMessageId : undefined, replyMessage, message.id);\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn]);\n\n const handleGroupDocumentMessagesSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n\n toggleMessageSelection({\n messageId,\n groupedId: message.groupedId,\n });\n }, [messageId, message.groupedId, toggleMessageSelection]);\n\n const handleMessageSelect = useCallback((e?: ReactMouseEvent) => {\n const params = isAlbum && album && album.messages\n ? {\n messageId,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: e && e.shiftKey,\n }\n : { messageId, withShift: e && e.shiftKey };\n toggleMessageSelection(params);\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n }, []);\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isChatPrivate(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n return;\n }\n\n if (isChatPrivate(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({ chatId, threadId, messageId: message.replyToMessageId });\n }, [focusMessage, chatId, threadId, message.replyToMessageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId: message.groupedId });\n }, [openForwardMenu, chatId, message.groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId: message.groupedId, groupedChatId: chatId,\n });\n return;\n }\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }, [focusMessage, forwardInfo, message, chatId, isInDocumentGroup]);\n\n const lang = useLang();\n\n let style = '';\n let calculatedWidth;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), album!, windowWidth) : undefined;\n }, [isAlbum, windowWidth, isOwn, asForwarded, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), width);\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), albumLayout.containerStyle.width);\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id);\n const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined;\n const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined;\n const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts &&

{textParts}

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

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n \n \n \n \n );\n case HeaderContent.ManageInitial:\n return

{lang('Edit')}

;\n case HeaderContent.ManageChatPrivacyType:\n return

{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}

;\n case HeaderContent.ManageDiscussion:\n return

{lang('Discussion')}

;\n case HeaderContent.ManageChatAdministrators:\n return

{lang('ChannelAdministrators')}

;\n case HeaderContent.ManageGroupRecentActions:\n return

{lang('Group.Info.AdminLog')}

;\n case HeaderContent.ManageGroupAdminRights:\n return

{lang('EditAdminRights')}

;\n case HeaderContent.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

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

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

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

{lang('GroupMembers')}

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

Profile

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

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {isVerifiedIconShown && }\n
\n )}\n {!isSavedMessages && renderStatus()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const {\n animationLevel,\n } = global.settings.byKey;\n\n return {\n lastSyncTime, user, chat, isSavedMessages, animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import {\n ApiChat, ApiMediaFormat, ApiPhoto, ApiUser,\n} from '../../../api/types';\nimport { useEffect } from '../../../lib/teact/teact';\nimport * as mediaLoader from '../../../util/mediaLoader';\n\nconst PHOTOS_TO_PRELOAD = 4;\n\nexport default function usePhotosPreload(\n profile: ApiUser | ApiChat | undefined,\n photos: ApiPhoto[],\n currentIndex: number,\n) {\n useEffect(() => {\n photos.slice(currentIndex, currentIndex + PHOTOS_TO_PRELOAD).forEach((photo) => {\n const mediaData = mediaLoader.getFromMemory(`photo${photo.id}?size=c`);\n if (!mediaData) {\n mediaLoader.fetch(`photo${photo.id}?size=c`, ApiMediaFormat.BlobUrl);\n }\n });\n }, [currentIndex, photos]);\n}\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { copyTextToClipboard } from '../../util/clipboard';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\nimport ListItem from '../ui/ListItem';\nimport Switcher from '../ui/Switcher';\n\ntype OwnProps = {\n chatOrUserId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n canInviteUsers?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst ChatExtra: FC = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n loadFullUser,\n showNotification,\n updateChatMutedState,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n const {\n id: chatId,\n isMuted: currentIsMuted,\n username: chatUsername,\n } = chat || {};\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const handleClick = useCallback((text: string, entity: string) => {\n copyTextToClipboard(text);\n showNotification({ message: `${entity} was copied` });\n }, [showNotification]);\n\n const handleNotificationChange = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !currentIsMuted });\n }, [chatId, currentIsMuted, updateChatMutedState]);\n\n if (!chat || chat.isRestricted || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n const bio = fullInfo && fullInfo.bio;\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n const description = getChatDescription(chat);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n const printedUsername = username || chatUsername;\n const printedDescription = bio || description;\n\n return (\n
\n {formattedNumber && !!formattedNumber.length && (\n handleClick(formattedNumber, lang('Phone'))}>\n {formattedNumber}\n {lang('Phone')}\n \n )}\n {printedUsername && (\n handleClick(`@${printedUsername}`, lang('Username'))}\n >\n {renderText(printedUsername)}\n {lang('Username')}\n \n )}\n {printedDescription && !!printedDescription.length && (\n handleClick(printedDescription, lang(userId ? 'UserBio' : 'Info'))}\n >\n {renderText(printedDescription, ['br', 'links', 'emoji'])}\n {lang(userId ? 'UserBio' : 'Info')}\n \n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n handleClick(link, lang('SetUrlPlaceholder'))}>\n
\n \n
\n {lang('SetUrlPlaceholder')}\n
\n )}\n \n {lang('Notifications')}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n const { lastSyncTime } = global;\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadFullUser', 'updateChatMutedState', 'showNotification',\n ]),\n)(ChatExtra));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType,\n} from '../../types';\n\nimport {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n isChatAdmin, isChatChannel, isChatGroup, isChatPrivate,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport ProfileInfo from './ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from './ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: number;\n userId?: number;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n members,\n usersById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n setLocalMediaSearchType,\n loadMoreMembers,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ]), [hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n usersById, chatMessages, foundIds, chatId, lastSyncTime,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'documents':\n text = 'No documents found.';\n break;\n case 'links':\n text = 'No links found.';\n break;\n case 'audio':\n text = 'No audio found.';\n break;\n default:\n text = 'No media found.';\n }\n\n return (\n
\n \n
\n );\n }\n\n return (\n
\n {resultType === 'media' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n
\n \n {renderSharedMedia}\n \n \n
\n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\n return (\n
\n \n \n
\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n\n let resolvedUserId;\n if (userId) {\n resolvedUserId = userId;\n } else if (isChatPrivate(chatId)) {\n resolvedUserId = chatId;\n }\n\n return {\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n ...(hasMembersTab && members && {\n members,\n usersById,\n }),\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat && chat.isRestricted,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default RightSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default ManagementAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default StickerSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default GifSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default PollResultsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState, RightColumnContent } from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: number;\n threadId?: number;\n currentProfileUserId?: number;\n isChatSelected: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\n ]),\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? : undefined;\n};\n\nexport default NotificationsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ErrorsAsync: FC = ({ isOpen }) => {\n const Errors = useModuleLoader(Bundles.Extra, 'Errors', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Errors ? : undefined;\n};\n\nexport default ErrorsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? : undefined;\n};\n\nexport default ForwardPickerAsync;\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n ANIMATION_END_DELAY, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport Notifications from './Notifications.async';\nimport Errors from './Errors.async';\nimport ForwardPicker from './ForwardPicker.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n animationLevel: number;\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasErrors: boolean;\n audioMessage?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet rightColumnAnimationTimeout: number | undefined;\nlet notificationInterval: number | undefined;\n\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n loadAnimatedEmojis,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n loadAnimatedEmojis();\n }\n }, [lastSyncTime, loadAnimatedEmojis]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n // For animating components in portals (i.e. Notification)\n document.body.classList.toggle('is-right-column-shown', className.includes('right-column-open'));\n }, [className]);\n\n // Add `body` classes when toggling right column\n useEffect(() => {\n if (animationLevel > 0) {\n document.body.classList.add('animating-right-column');\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n\n if (rightColumnAnimationTimeout) {\n clearTimeout(rightColumnAnimationTimeout);\n rightColumnAnimationTimeout = undefined;\n }\n\n rightColumnAnimationTimeout = window.setTimeout(() => {\n document.body.classList.remove('animating-right-column');\n rightColumnAnimationTimeout = undefined;\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isRightColumnShown]);\n\n useBackgroundMode(() => {\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n document.title = `${newUnread} notification${newUnread > 1 ? 's' : ''}`;\n updateIcon(true);\n }\n } else {\n document.title = PAGE_TITLE;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n document.title = PAGE_TITLE;\n }\n\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasErrors: Boolean(global.errors.length),\n audioMessage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis']),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/3.4cc830a94ce5c77c6a75.js.map b/dist/3.4cc830a94ce5c77c6a75.js.map deleted file mode 100644 index 2800b2cf..00000000 --- a/dist/3.4cc830a94ce5c77c6a75.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///./src/modules/actions/ui/chats.ts","webpack:///./src/modules/actions/ui/messages.ts","webpack:///./src/modules/actions/ui/globalSearch.ts","webpack:///./src/modules/actions/ui/localSearch.ts","webpack:///./src/modules/actions/ui/stickerSearch.ts","webpack:///./src/modules/actions/ui/users.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/ui/misc.ts","webpack:///./src/modules/actions/ui/payments.ts","webpack:///./src/modules/actions/api/chats.ts","webpack:///./src/modules/actions/api/messages.ts","webpack:///./src/modules/actions/api/symbols.ts","webpack:///./src/modules/actions/api/globalSearch.ts","webpack:///./src/modules/actions/api/localSearch.ts","webpack:///./src/modules/actions/api/management.ts","webpack:///./src/modules/actions/api/sync.ts","webpack:///./src/modules/actions/api/users.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/api/bots.ts","webpack:///./src/modules/actions/api/twoFaSettings.ts","webpack:///./src/modules/actions/api/payments.ts","webpack:///./src/util/requestQuery.ts","webpack:///./src/modules/actions/apiUpdaters/chats.ts","webpack:///./src/modules/actions/apiUpdaters/messages.ts","webpack:///./src/modules/actions/apiUpdaters/users.ts","webpack:///./src/modules/actions/apiUpdaters/symbols.ts","webpack:///./src/modules/actions/apiUpdaters/misc.ts","webpack:///./src/modules/actions/apiUpdaters/settings.ts","webpack:///./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack:///./src/components/ui/Switcher.tsx","webpack:///./src/components/left/main/LeftMainHeader.tsx","webpack:///./src/components/left/ConnectionState.tsx","webpack:///./src/hooks/useThrottledMemo.ts","webpack:///./src/hooks/useThrottle.ts","webpack:///./src/components/left/main/ChatFolders.tsx","webpack:///./src/components/left/search/LeftSearch.async.tsx","webpack:///./src/components/left/main/ContactList.async.tsx","webpack:///./src/components/left/NewChatButton.tsx","webpack:///./src/components/left/main/LeftMain.tsx","webpack:///./src/components/left/settings/Settings.async.tsx","webpack:///./src/components/left/newChat/NewChat.async.tsx","webpack:///./src/components/left/ArchivedChats.async.tsx","webpack:///./src/components/left/LeftColumn.tsx","webpack:///./src/hooks/useWindowSize.ts","webpack:///./src/hooks/usePrevForAnimation.ts","webpack:///./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack:///./src/hooks/useCurrentOrPrev.ts","webpack:///./src/components/middle/HeaderMenuContainer.async.tsx","webpack:///./src/components/middle/HeaderActions.tsx","webpack:///./src/hooks/useWebpThumbnail.ts","webpack:///./src/components/middle/PinnedMessageNavigation.tsx","webpack:///./src/components/middle/HeaderPinnedMessage.tsx","webpack:///./src/components/middle/AudioPlayer.tsx","webpack:///./src/components/middle/MiddleHeader.tsx","webpack:///./src/components/middle/helpers/groupMessages.ts","webpack:///./src/components/middle/hooks/useStickyDates.ts","webpack:///./src/hooks/useDebounce.ts","webpack:///./src/components/middle/MessageScroll.tsx","webpack:///./src/components/middle/message/helpers/buildContentClassName.ts","webpack:///./src/components/middle/message/helpers/mediaDimensions.ts","webpack:///./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack:///./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack:///./src/components/middle/message/hooks/useFocusMessage.ts","webpack:///./src/components/middle/message/ContextMenuContainer.async.tsx","webpack:///./src/components/middle/ActionMessage.tsx","webpack:///./src/components/common/EmbeddedMessage.tsx","webpack:///./src/components/middle/message/MessageMeta.tsx","webpack:///./src/components/middle/message/Sticker.tsx","webpack:///./src/components/middle/message/hooks/useBlurredMediaThumb.ts","webpack:///./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack:///./src/components/middle/message/Photo.tsx","webpack:///./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack:///./src/components/middle/message/Video.tsx","webpack:///./src/components/middle/message/Contact.tsx","webpack:///./src/components/ui/CheckboxGroup.tsx","webpack:///./src/components/middle/message/PollOption.tsx","webpack:///./src/components/middle/message/Poll.tsx","webpack:///./src/components/middle/message/WebPage.tsx","webpack:///./src/components/middle/message/Invoice.tsx","webpack:///./src/components/middle/message/hocs/withSelectControl.tsx","webpack:///./src/components/middle/message/Album.tsx","webpack:///./src/components/middle/message/RoundVideo.tsx","webpack:///./src/components/middle/message/InlineButtons.tsx","webpack:///./src/components/middle/message/CommentButton.tsx","webpack:///./src/components/middle/message/Message.tsx","webpack:///./src/components/middle/MessageList.tsx","webpack:///./src/components/middle/ScrollDownButton.tsx","webpack:///./src/components/middle/composer/helpers/buildAttachment.ts","webpack:///./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack:///./src/util/voiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack:///./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack:///./src/components/middle/composer/hooks/useDraft.ts","webpack:///./src/components/common/DeleteMessageModal.async.tsx","webpack:///./src/components/ui/ResponsiveHoverButton.tsx","webpack:///./src/components/middle/composer/AttachMenu.async.tsx","webpack:///./src/components/middle/composer/SymbolMenu.async.tsx","webpack:///./src/components/middle/composer/MentionMenu.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.async.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.async.tsx","webpack:///./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack:///./src/components/middle/composer/AttachmentModal.async.tsx","webpack:///./src/components/middle/composer/PollModal.async.tsx","webpack:///./src/components/middle/composer/DropArea.async.tsx","webpack:///./src/components/middle/composer/WebPagePreview.tsx","webpack:///./src/components/common/CalendarModal.async.tsx","webpack:///./src/components/payment/PaymentModal.async.tsx","webpack:///./src/components/payment/ReceiptModal.async.tsx","webpack:///./src/components/middle/composer/Composer.tsx","webpack:///./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useEmojiTooltip.ts","webpack:///./src/util/insertHtmlInSelection.ts","webpack:///./src/util/deleteLastCharacterOutsideSelection.ts","webpack:///./src/components/middle/composer/hooks/useEditing.ts","webpack:///./src/components/middle/MobileSearch.async.tsx","webpack:///./src/components/middle/MessageSelectToolbar.async.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.async.tsx","webpack:///./src/components/middle/MiddleColumn.tsx","webpack:///./src/hooks/useCustomBackground.ts","webpack:///./src/components/right/RightHeader.tsx","webpack:///./src/components/right/hooks/useProfileViewportIds.ts","webpack:///./src/components/right/hooks/useProfileState.ts","webpack:///./src/components/right/ProfilePhoto.tsx","webpack:///./src/components/right/ProfileInfo.tsx","webpack:///./src/components/right/hooks/usePhotosPreload.ts","webpack:///./src/components/right/ChatExtra.tsx","webpack:///./src/components/right/Profile.tsx","webpack:///./src/components/right/hooks/useTransitionFixes.ts","webpack:///./src/hooks/useCacheBuster.ts","webpack:///./src/components/right/RightSearch.async.tsx","webpack:///./src/components/right/management/Management.async.tsx","webpack:///./src/components/right/StickerSearch.async.tsx","webpack:///./src/components/right/GifSearch.async.tsx","webpack:///./src/components/right/PollResults.async.tsx","webpack:///./src/components/right/RightColumn.tsx","webpack:///./src/components/mediaViewer/MediaViewer.async.tsx","webpack:///./src/components/main/Notifications.async.tsx","webpack:///./src/components/main/Errors.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["window","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","audioPlayer","selectIsRightColumnShown","pollResults","voters","setTimeout","newGlobal","getGlobal","lastMessageId","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","focusMessage","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","length","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","Static","includes","direction","Down","Up","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","management","byChatId","isActive","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","Object","keys","draftsById","map","Number","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","IS_TOUCH_ENV","loadPinnedMessages","currentUserId","hasUnreadMark","toggleChatUnread","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","requestThreadInfoUpdate","selectSupportChat","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","date","force","isMuted","title","about","photo","memberIds","progress","ChatCreationProgress","InProgress","createdChannel","channelId","accessHash","Complete","Error","createChannel","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","emoticon","orderedIds","maxId","recommendedId","description","newFolder","createChatFolder","Math","max","apply","deleteChatFolder","unreadCount","url","match","RE_TME_INVITE_LINK","exec","RE_TME_LINK","isEnabled","isChatBasicGroup","bannedRights","userId","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","channel","fullChat","isPreHistoryHidden","linkedChatId","offset","uploadProgressCallbacks","Map","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","firstMessageId","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","slice","areSomeLocal","areAllLocal","sendMessage","params","localId","progressCallback","attachment","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","scheduledAt","setReplyingToId","clearWebPagePreview","value","selectReplyingToId","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","v","a","indexOf","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","copyTextToClipboard","link","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","setsById","searchWords","searchStickers","updateStickersForEmoji","loadStickersForEmoji","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","localChats","localUsers","globalChats","globalUsers","userIds","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","contactIds","contactList","updatedUsers","afterSyncCallback","DEBUG","console","log","notifyClientReady","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isChatPrivate","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","draftsByChatId","acc","lastReadInboxMessageId","newCurrentChatId","currentMessageListInfo","threadsById","Array","prototype","concat","replaceUsers","loadAndReplaceMessages","lastSyncTime","sync","afterSync","runDebouncedForFetchFullUser","buildInputPrivacyRules","visibility","allowedIds","deniedIds","usersById","chatsById","rules","collectUsers","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","lastRequestedAt","topPeers","usersHash","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","updateChatMutedState","phone","phoneNumber","updateUser","updateContact","deleteUser","profileId","isPrivate","photos","button","sendBotCommand","command","openTelegramLink","open","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","settings","loadedWallpapers","wallpapers","file","previewBlobUrl","URL","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","document","fileName","size","mimeType","wallpaper","firstWallpaper","withLocalMedia","blocked","blockedIds","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","peerType","isShowPreviews","updateNotifySettings","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isLoading","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","Shipping","PaymentInfo","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","ShippingInfo","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","join","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","Checkout","sendStipeCredentials","shippingOptionId","saveCredentials","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","update","selectIsChatListed","loadTopChats","newProfilePhoto","isNotJoined","listId","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","pick","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","updateWithLocalMedia","isScheduled","currentMessage","video","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","updateScheduledMessage","updateListedAndViewportIds","selectIsViewportNewest","addViewportId","selectThreadByMessage","isMessageLocal","updateChatLastMessage","currentLastMessage","findLastMessage","isDeleting","deleteMessages","newLastMessage","threadIdsToUpdate","unique","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","updateThreadInfo","newMessage","isMessageInCurrentMessageList","isOutgoing","scheduledIds","selectScheduledIds","selectScheduledMessages","deleteChatScheduledMessages","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","poll","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","newResults","targetOption","targetOptionIndex","updatedOption","votersCount","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","key","twoFaSettings","memo","name","label","checked","disabled","inactive","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","theme","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","isNewThemeDark","customBackground","DARK_THEME_BG_COLOR","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","lang","useLang","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_INFO","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","SearchInput","inputId","focused","placeholder","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","transitionRef","activeTab","setActiveTab","useState","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","captureEvents","onSwipe","SwipeDirection","Left","min","Right","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","onSwitchTab","Transition","ref","activeKey","renderCount","LeftSearchAsync","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactListAsync","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","SettingsAsync","NewChatAsync","NewChat","ArchivedChatsAsync","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","captureEscKeyListener","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","removeEventListener","usePrevForAnimation","duration","prev","usePrevious","timeoutRef","isCurrentPresent","calculateMiddleFooterTransforms","windowWidth","canPost","sidePadding","MOBILE_SCREEN_MAX_WIDTH","messageListWidth","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","leftColumnWidth","rightColumnWidth","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","useCurrentOrPrev","shouldSkipUndefined","shouldForceCurrent","HeaderMenuContainerAsync","HeaderMenuContainer","isChatChannel","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canSelect","selectIsInSelectMode","canLeave","joinChannel","openLocalTextSearch","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleSearchClick","querySelector","focus","searchInput","fluid","anchor","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","width","height","radius","count","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","style","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","useFlag","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","senderName","getSenderTitle","noUi","closeAudioPlayer","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioChatId","audioMessageId","audioMessage","originChat","messagesCount","pinnedIds","isSelectModeActive","chatTitleLength","getChatTitle","originChatId","isChatWithBot","selectIsChatWithBot","pinnedMessageIds","firstPinnedMessage","canUnpin","pinnedMessageId","selectForwardedSender","topMessageTitle","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","cycleRestrict","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","newIndex","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","componentEl","add","remove","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","isAlbum","messageOrAlbum","groupMessages","firstUnreadId","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","isFabFrozen","MessageScroll","containerHeight","listItemElementsRef","focusingId","anchorIdRef","anchorTopRef","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","updateFabVisibility","scrollHeight","scrollBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","dataset","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","preservedItemElements","element","teactFastList","data-is-active","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","calculateMediaDimensions","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","AlbumRectPart","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","album","ratios","proportions","ratio","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","REM","getMaxWidth","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","calculateAuthorWidth","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainerAsync","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","senderTitle","MessageMeta","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","Sticker","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","shouldRenderFullMedia","useTransitionForMedia","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumb","fullMediaData","useBlur","LAYERS_TRANSITION_DURATION","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","isPlayAllowed","setIsPlayAllowed","previewMediaData","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","useVideoCleanup","videoClassName","videoStyle","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","event","newValues","Checkbox","subLabel","getPercentage","toFixed","PollOption","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","floor","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","question","getPollTypeString","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","hasDocument","siteName","displayUrl","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","toString","stopPlaying","requestAnimationFrame","capturePlaying","onRelease","paused","ROUND_VIDEO_DIMENSIONS","poster","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","formatInteger","renderLabel","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","forceSenderName","isAnonymousOwnMessage","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","selectOutgoingStatus","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","shouldAutoLoadMedia","selectShouldAutoLoadMedia","shouldAutoPlayMedia","selectShouldAutoPlayMedia","shouldLoopStickers","selectShouldLoopStickers","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","isLastInList","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","clickInlineButton","bottomMarkerRef","appendixRef","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","avatarPeer","senderPeer","adminTitle","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","showCommentsButton","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","runThrottledOnTickEnd","throttleWithTickEnd","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","getCanPostInChat","selectFirstUnreadId","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","bottomOffset","markMessageListRead","setScrollOffset","scrollOffsetRef","selectScrollOffset","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","normalHeight","String","IS_IOS","webkitOverflowScrolling","clientHeight","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","isAtBottom","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isResized","unreadDivider","isAnimatingScroll","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","shouldRenderUnreadDivider","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messsageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","startsWith","preloadImage","newBlob","toBlob","squeezeImage","revokeObjectURL","videoWidth","videoHeight","preloadVideo","createPosterForVideo","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","startedAt","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","volume","subscribeToAnalyzer","stop","reject","onstop","Blob","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","formattedText","currentThreadId","DeleteMessageModalAsync","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenuAsync","AttachMenu","SymbolMenuAsync","SymbolMenu","MentionMenuAsync","MentionMenu","CustomSendMenuAsync","CustomSend","EmojiTooltipAsync","EmojiTooltip","BotKeyboardMenuAsync","BotKeyboardMenu","forwardMessageIds","replyingToId","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModalAsync","AttachmentModal","PollModalAsync","PollModal","DropAreaAsync","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModalAsync","CalendarModal","PaymentModalAsync","PaymentModal","ReceiptModalAsync","MainButtonState","ReceiptModal","chatUser","selectChatUser","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionMenuOpen","mentionFilter","closeMentionMenu","insertMention","mentionFilteredMembers","useMentionMenu","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isEmojiTooltipOpen","closeEmojiTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useEmojiTooltip","canSendStickers","insertTextAndUpdateCursor","selection","getSelection","newHtml","replace","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","execCommand","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","prevChatId","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","tagName","EDITABLE_INPUT_MODAL_ID","items","media","getAsFile","pastedText","getData","substring","preventDefault","useClipboardPaste","handleFileSelect","files","handleClearAttachment","handleSend","currentAttachments","record","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","Portal","containerId","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","onPollCreate","onEmojiSelect","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","selectedAt","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearchAsync","MobileSearch","MessageSelectToolbarAsync","MessageSelectToolbar","UnpinAllMessagesModalAsync","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBackgroundBlurred","isCustomBackgroundColor","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","isMobileSearchActive","loadUser","setDropAreaState","isFabShown","setIsFabShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","renderingThreadId","renderingMessageListType","renderingCanPost","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_ENABLED","messagingDisabledClassName","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleJumpToDate","valueOf","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","isPastMode","submitButtonLabel","useProfileViewportIds","loadMoreMembers","searchMessages","tabType","mediaSearchType","resultType","sortUserIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","currentResultType","handleLoadMore","getMore","useInfiniteScroll","MEMBERS_SLICE","isOnTop","useInfiniteScrollForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","useInfiniteScrollForSharedMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","noProfileInfo","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","isFirstPhoto","isSavedMessages","isDeleted","isDeletedUser","getMediaHash","forceAvatar","getChatAvatarHash","imageHash","ApiMediaFormat","BlobUrl","avatarThumbnailData","useBlurSync","dataUri","imageSrc","prevImageSrc","decoding","userFullName","getUserFullName","getFirstLetters","fullClassName","forceShowSelf","loadFullUser","fullName","slideAnimation","currentPhotoIndex","setCurrentPhotoIndex","isFirst","isLast","profile","currentIndex","usePhotosPreload","handleProfilePhotoClick","ProfileAvatar","selectPreviousMedia","selectNextMedia","excludedClosestSelector","renderPhoto","isVerifiedIconShown","isVerified","renderPhotoTabs","aria-label","VerifiedIcon","isUserOnline","getUserStatus","canInviteUsers","isUserRightBanned","getHasAdminRight","currentIsMuted","chatUsername","entity","handleNotificationChange","formattedNumber","getChatDescription","getChatLink","printedUsername","printedDescription","ListItem","multiline","narrow","TABS","buildInfiniteScrollItemSelector","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","loadProfilePhotos","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","RightSearchAsync","RightSearch","ManagementAsync","Management","StickerSearchAsync","GifSearchAsync","PollResultsAsync","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","NotificationsAsync","ErrorsAsync","Errors","ForwardPickerAsync","ForwardPicker","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","useBackgroundMode","initialUnread","selectCountNotMutedUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","onDrop","onDragOver","initApi"],"mappings":"44BAOAA,OAAOC,iBAAiB,WAAaC,IACnC,IAAKA,EAAEC,MACL,OAGF,MAAQC,OAAQC,EAAV,SAAcC,EAAUC,gBAAiBC,GAASN,EAAEC,MAE1DM,cAAcC,SAAS,CACrBL,KAAIC,WA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MAAM00E,EAAYJ,YAA0B3mF,eAAe0mF,EACvDK,EAAY,IACdpjE,SAASnY,MAAS,GAAEu7E,iBAAyBA,EAAY,EAAI,IAAM,KACnEjB,IAAW,SAGbniE,SAASnY,MAAQw7E,KACjBlB,IAAW,GAGbzzE,MA5FwB,MA8FzB,KACDu0E,cAAchB,IACdA,QAAuB7nF,EAElB4lB,SAASnY,MAAMnK,SAASylF,OAC3BnjE,SAASnY,MAAQw7E,MAGnBlB,IAAW,KASX,yBAAK/oF,GAAG,OAAO6zB,UAAWA,EAAWq2D,OAAQT,EAAWU,WAAYV,GAClE,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,CAAa3zD,OAAQmzD,IACrB,kBAAC,GAAD,CAAenzD,OAAQqzD,IACvB,kBAAC,GAAD,CAAerzD,OAAQuzD,IACvB,kBAAC,GAAD,CAAQvzD,OAAQwzD,IACfx7C,GAAgB,kBAAC,GAAD,CAAa9a,IAAK8a,EAAa9tC,GAAI8I,QAASglC,EAAcnB,MAAI,QClKjF7rB,KAEFC,QAAQC,IAAI,+BAGT/d,cAAY81B,iBACf34B,cAAcgqF","file":"3.4cc830a94ce5c77c6a75.js","sourcesContent":["import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\n\nconst FOCUS_DURATION = 2000;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {},\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && ids.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n return toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n});\n\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings } from '../../../types';\nimport { replaceSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n const { id } = payload!;\n\n return {\n ...global,\n isLeftColumnShown: id === undefined,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: 0,\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global) => {\n const newNotifications = [...global.notifications];\n\n newNotifications.pop();\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showError', (global, actions, payload) => {\n const { error } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if (!getReadableErrorText(error)) {\n return global;\n }\n\n const newErrors = [...global.errors];\n const existingErrorIndex = newErrors.findIndex((err) => err.message === error.message);\n if (existingErrorIndex !== -1) {\n newErrors.splice(existingErrorIndex, 1);\n }\n\n newErrors.push(error);\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('dismissError', (global) => {\n const newErrors = [...global.errors];\n\n newErrors.pop();\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\nimport {\n clearPayment, closeInvoice,\n} from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n RE_TME_INVITE_LINK,\n RE_TME_LINK,\n TIPS_USERNAME,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n} from '../../reducers';\nimport {\n selectChat,\n selectCurrentChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\n\nconst TOP_CHATS_PRELOAD_PAUSE = 200;\n// We expect this ID does not exist\nconst TMP_CHAT_ID = -1;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), 1000, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForLoadFullChat = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: number[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHATS_PRELOAD_PAUSE);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n\n if (IS_TOUCH_ENV) {\n actions.loadPinnedMessages({ chatId: chatToPreload.id });\n }\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat && chat.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n\n actions.openChat({ id: chat ? chat.id : TMP_CHAT_ID });\n\n if (chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions) => {\n actions.openChatByUsername({ username: TIPS_USERNAME });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', chat);\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('updateChatMutedState', { chat, isMuted });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('leaveChannel', { channelId, accessHash });\n }\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('deleteChannel', { channelId, accessHash });\n }\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n let match = RE_TME_INVITE_LINK.exec(url);\n\n if (match) {\n const hash = match[1];\n\n (async () => {\n const chat = await callApi('openChatByInvite', hash);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n })();\n } else {\n match = RE_TME_LINK.exec(url)!;\n\n const username = match[1];\n const channelPostId = match[2] ? Number(match[2]) : undefined;\n\n void openChatByUsername(actions, username, channelPostId);\n }\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n void openChatByUsername(actions, username);\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById).map(Number),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo && channel.fullInfo.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: number, offsetDate?: number) {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: getGlobal().chats.orderedPinnedIds[listType] === undefined,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChat = await callApi('createGroupChat', { title, users });\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: chatId });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', { chatId, photo });\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n if (channelPostId) {\n actions.focusMessage({ chatId: localChat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: localChat.id });\n }\n return;\n }\n\n const previousChat = selectCurrentChat(global);\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n if (previousChat) {\n actions.openChat({ id: previousChat.id });\n }\n\n actions.showNotification({ message: 'User does not exist' });\n\n return;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE } from '../../../config';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport { areSortedArraysIntersecting, buildCollectionByKey, split } from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n} from '../../selectors';\nimport { rafPromise } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map();\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const { chatId, messageId, replyOriginForId } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void loadMessage(chat, messageId, replyOriginForId);\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', draft);\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n const { chatId, maxId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n const { maxId } = payload!;\n\n void callApi('markMessageListRead', { chat, threadId, maxId });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter(Boolean as any)\n : undefined;\n\n if (fromChat && toChat && messages && messages.length) {\n void forwardMessages(fromChat, toChat, messages);\n }\n});\n\naddReducer('loadScheduledHistory', (global) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { hash } = global.scheduledMessages.byChatId[chat.id] || {};\n\n void loadScheduledHistory(chat, hash);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos, firstMessageId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\n chat: ApiChat;\n text: string;\n entities: ApiMessageEntity[];\n replyingTo: number;\n attachment: ApiAttachment;\n sticker: ApiSticker;\n gif: ApiVideo;\n poll: ApiNewPoll;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo) {\n await rafPromise();\n }\n\n const global = getGlobal();\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nfunction forwardMessages(\n fromChat: ApiChat,\n toChat: ApiChat,\n messages: ApiMessage[],\n) {\n callApi('forwardMessages', {\n fromChat,\n toChat,\n messages,\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n const isUnique = (v: number, i: number, a: number[]) => a.indexOf(v) === i;\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: [\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ].filter(isUnique),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadMessageLink', (global, actions, payload) => {\n const { messageId, chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchMessageLink', { chat, message });\n\n if (result) {\n copyTextToClipboard(result.link);\n }\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat, historyHash?: number) {\n const result = await callApi('fetchScheduledHistory', { chat, hash: historyHash });\n if (!result) {\n return;\n }\n\n const { hash, messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId, hash);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\nasync function loadStickerSets(hash = 0) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash = 0) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash = 0) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash = 0) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string) {\n const stickerSet = await callApi('fetchStickers', { stickerSetId, accessHash });\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\nasync function searchStickers(query: string, hash = 0) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash = 0) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash = 0) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {};\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalUsers.map(({ id }) => id),\n userIds: globalChats.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results ? results.nextOffsetId : undefined;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo ? threadInfo.topMessageId : undefined;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults ? currentResults.nextOffsetId : undefined;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { notifyClientReady } from '../../../util/pushNotifications';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n} from '../../reducers';\nimport {\n selectUser, selectChat, selectCurrentMessageList, selectDraft,\n} from '../../selectors';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n });\n if (!result) {\n return undefined;\n }\n\n let global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isChatPrivate(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n });\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n return draft ? { ...acc, [chatId]: draft } : acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const byId = buildCollectionByKey(result.messages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n [currentChatId]: {\n byId,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]),\n listedIds,\n viewportIds: listedIds,\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).map(Number).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, updateManagementProgress, updateUser, updateUsers,\n} from '../../reducers';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60000; // 1 min\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { hash, lastRequestedAt } = global.topPeers;\n\n if (!lastRequestedAt || Date.now() - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers(hash);\n }\n});\n\naddReducer('loadContactList', (global) => {\n const { hash } = global.contactList || {};\n void loadContactList(hash);\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers(usersHash?: number) {\n const result = await callApi('fetchTopUsers', { hash: usersHash });\n if (!result) {\n return;\n }\n\n const { hash, ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n hash,\n userIds: ids,\n lastRequestedAt: Date.now(),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList(hash?: number) {\n const contactList = await callApi('fetchContactList', { hash });\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n hash: contactList.hash,\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: number,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n const result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: number) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteUser', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isChatPrivate(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationsSettings', () => {\n (async () => {\n const result = await callApi('loadNotificationsSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, isShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, isShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, isShowPreviews));\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: number) => {\n if (isChatPrivate(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n","import { addReducer, getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { RE_TME_INVITE_LINK, RE_TME_LINK } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChatMessage, selectCurrentChat } from '../../selectors';\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_INVITE_LINK) || button.value.match(RE_TME_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n window.open(button.value);\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n if (!currentUserId || !chat) {\n return;\n }\n\n void sendBotCommand(chat, currentUserId, command);\n});\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: number, command: string) {\n await callApi('sendMessage', {\n chat,\n text: command,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result || !result.message) {\n return;\n }\n\n const { message, alert: isError } = result;\n\n if (isError) {\n getDispatch().showError({ error: { message } });\n } else {\n getDispatch().showNotification({ message });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types/index';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n} from '../../selectors';\n\nimport { getStripeError } from '../../helpers/payments';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const messageId = selectPaymentMessageId(global);\n if (!messageId) {\n return;\n }\n validateRequestedInfo(messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', { messageId, requestInfo, shouldSave });\n if (!result) {\n return;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { messageId } = payload;\n if (!messageId) {\n return;\n }\n getPaymentForm(messageId);\n});\n\n\nasync function getPaymentForm(messageId: number) {\n const result = await callApi('getPaymentForm', { messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n if (!messageId || !receiptMessageId || !chatId) {\n return;\n }\n getReceipt(messageId, receiptMessageId, chatId);\n});\n\nasync function getReceipt(messageId: number, receiptMessageId: number, chatId: number) {\n const result = await callApi('getReceipt', receiptMessageId);\n if (!result) {\n return;\n }\n let global = getGlobal();\n const message = selectChatMessage(global, chatId, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n sendStipeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const messageId = selectPaymentMessageId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!messageId || !publishableKey) {\n return;\n }\n sendPaymentForm(messageId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStipeCredentials(data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n},\npublishableKey: string) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n messageId: number,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n messageId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n} from '../../selectors';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1000;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n setGlobal(updateChat(global, update.id, update.chat, update.newProfilePhoto));\n\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== update.id));\n }\n\n global = updateChat(global, update.id, { isNotJoined: true });\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n if (update.chatId === currentChatId) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id);\n const chat = selectChat(global, chatId);\n if (chat && chat.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo && targetChat.fullInfo.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat && chat.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { getMessageContent, isChatPrivate, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const { chatId, id, message } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content && message.content.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!message.isOutgoing) {\n setTimeout(() => {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds]\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const { chatId, threadId, threadInfo } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isChatPrivate(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const ids = Object.keys(global.messages.byChatId[chatId].byId).map(Number);\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message && message.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: number, id: number, message: Partial, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, message: ApiMessage) {\n const { id, chatId } = message;\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n global = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n }\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!firstMessageId && isMessageLocal(message)) {\n return global;\n }\n\n if (threadInfo) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n\n if (!threadInfo.lastMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n });\n }\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: number,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId] && chats.byId[chatId].lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: number) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, updateUser } from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: [number, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: number, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n hash: 0,\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.isShowPreviews);\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Switcher.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n checked?: boolean;\n disabled?: boolean;\n inactive?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC = ({\n id,\n name,\n value,\n label,\n checked = false,\n disabled,\n inactive,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((e: ChangeEvent) => {\n if (onChange) {\n onChange(e);\n }\n\n if (onCheck) {\n onCheck(e.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n inactive && 'inactive',\n );\n\n return (\n \n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n APP_INFO, DEFAULT_PATTERN_COLOR, FEEDBACK_URL, DARK_THEME_BG_COLOR, DARK_THEME_PATTERN_COLOR,\n} from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n onReset()}\n ariaLabel={hasMenu ? 'Open menu' : 'Return to chat list'}\n >\n
\n \n );\n }, [hasMenu, onReset]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n const isNewThemeDark = newTheme === 'dark';\n\n setSettingOption({\n theme: newTheme,\n customBackground: isNewThemeDark ? DARK_THEME_BG_COLOR : undefined,\n patternColor: isNewThemeDark ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n switchTheme(newTheme, animationLevel > 0);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const lang = useLang();\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n
\n
\n \n \n {lang('SavedMessages')}\n \n \n {lang('ArchivedChats')}\n {archivedUnreadChatsCount > 0 && (\n
{archivedUnreadChatsCount}
\n )}\n \n \n {lang('Contacts')}\n \n \n {lang('Settings')}\n \n \n Dark Mode\n \n \n \n {lang('Appearance.Animations').toLowerCase()}\n 0}\n />\n \n \n Telegram Features\n \n \n Report Bug\n \n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { theme, animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { FC } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = ({ connectionState }) => {\n const lang = useLang();\n\n const isConnecting = connectionState === 'connectionStateConnecting';\n\n return isConnecting && (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef();\n const runThrottled = useThrottle(ms);\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n let isSync = true;\n runThrottled(() => {\n valueRef.current = resolverFn();\n\n if (!isSync) {\n forceUpdate();\n }\n });\n isSync = false;\n }, dependencies);\n\n return valueRef.current;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms);\n }, [ms]);\n};\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n orderedFolderIds?: number[];\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst INFO_THROTTLE = 3000;\n\nconst ChatFolders: FC = ({\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n loadChatFolders,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: 'All' },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveTab(index);\n }, []);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeTab >= folderTabs.length) {\n setActiveTab(0);\n }\n }, [activeTab, folderTabs]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, folderTabs]);\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n const lang = useLang();\n\n function renderCurrentTab() {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ title }) => title === folderTabs![activeTab].title);\n\n if (!activeFolder || activeTab === 0) {\n return ;\n }\n\n return ;\n }\n\n return (\n
\n {folderTabs && folderTabs.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n },\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadChatFolders']),\n)(ChatFolders));\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? : ;\n};\n\nexport default LeftSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? : ;\n};\n\nexport default ContactListAsync;\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n New Private Chat\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, memo, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = {};\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\n onReset,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n return (\n \n \n \n \n {() => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n \n
\n );\n};\n\nexport default memo(LeftMain);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? : ;\n};\n\nexport default SettingsAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? : ;\n};\n\nexport default NewChatAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? : ;\n};\n\nexport default ArchivedChatsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n};\n\ntype DispatchProps = Pick;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC = ({\n searchQuery,\n searchDate,\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n}) => {\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n default:\n break;\n }\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [content, setGlobalSearchQuery, setGlobalSearchChatId, setGlobalSearchDate, resetChatCreation, settingsScreen]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList ? captureEscKeyListener(() => handleReset()) : undefined),\n [content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n return (\n \n {() => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n \n );\n case ContentType.Settings:\n return (\n \n );\n case ContentType.NewChannel:\n return (\n \n );\n case ContentType.NewGroup:\n return (\n \n );\n default:\n return (\n \n );\n }\n }}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { query, date } = global.globalSearch;\n return { searchQuery: query, searchDate: date };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError',\n ]),\n)(LeftColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { IDimensions } from '../modules/helpers';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\n\nconst RESIZE_TIMEOUT_MS = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, RESIZE_TIMEOUT_MS, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n });\n\n return size;\n};\n","import { useRef } from '../lib/teact/teact';\n\nimport usePrevious from './usePrevious';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport default function usePrevForAnimation(current: any, duration?: number) {\n const prev = usePrevious(current, true);\n const timeoutRef = useRef();\n const forceUpdate = useForceUpdate();\n // eslint-disable-next-line no-null/no-null\n const isCurrentPresent = current !== undefined && current !== null;\n\n if (isCurrentPresent && timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useOnChange(() => {\n // When `current` becomes empty\n if (duration && !isCurrentPresent && prev && !timeoutRef.current) {\n timeoutRef.current = window.setTimeout(() => {\n timeoutRef.current = undefined;\n forceUpdate();\n }, duration);\n }\n }, [current]);\n\n return isCurrentPresent || (duration && !timeoutRef.current) ? current : prev;\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import usePrevious from './usePrevious';\n\nexport default function useCurrentOrPrev(\n current: T, shouldSkipUndefined = false, shouldForceCurrent = false,\n): T | undefined {\n const prev = usePrevious(current, shouldSkipUndefined);\n\n // eslint-disable-next-line no-null/no-null\n return shouldForceCurrent || (current !== null && current !== undefined) ? current : prev;\n}\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default HeaderMenuContainerAsync;\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectIsChatBotNotStarted, selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick;\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n isRightColumnShown,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_MOBILE_SCREEN) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n const lang = useLang();\n\n return (\n
\n {!IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {!IS_MOBILE_SCREEN && canStartBot && (\n \n {lang('Start')}\n \n )}\n {!IS_MOBILE_SCREEN && canSearch && (\n \n \n \n )}\n {(IS_MOBILE_SCREEN || !canSubscribe) && (\n \n \n \n )}\n {menuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (chat && chat.isRestricted) {\n return {\n noMenu: true,\n };\n }\n\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canStartBot = Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canSelect = !selectIsInSelectMode(global);\n const canLeave = isMainThread && !canSubscribe;\n\n const noMenu = !(\n (IS_MOBILE_SCREEN && canSubscribe)\n || (IS_MOBILE_SCREEN && canSearch)\n || canMute\n || canSelect\n || canLeave\n );\n\n return {\n noMenu,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbnail = message && getMessageMediaThumbDataUri(message);\n const { sticker } = (message && message.content) || {};\n const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message && message.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbnail!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbnail]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbnail;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef && containerRef.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n
\n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n const lang = useLang();\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiAudio, ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageAudio, getMessageKey, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n senderName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst AudioPlayer: FC = ({\n message, className, noUi, senderName, focusMessage, closeAudioPlayer,\n}) => {\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const { playPause, isPlaying } = useAudioPlayer(\n getMessageKey(message), getMediaDuration(message)!, mediaData, undefined, undefined, true,\n );\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n }, [closeAudioPlayer, isPlaying, playPause]);\n\n const lang = useLang();\n\n if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n
\n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n \n
\n\n \n \n \n
\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n
{renderText(title || fileName)}
\n {performer && (\n
{renderText(performer)}
\n )}\n \n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n
{senderName && renderText(senderName)}
\n
{subtitle}
\n \n );\n}\n\nexport default withGlobal(\n (global, { message }) => {\n const sender = selectSender(global, message);\n const senderName = sender ? getSenderTitle(sender) : undefined;\n\n return { senderName };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage', 'closeAudioPlayer']),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiTypingStatus,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n isChatPrivate,\n isChatArchived,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadOriginChat,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n};\n\ntype StateProps = {\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageTitle?: string;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatTitleLength?: number;\n chatsById?: Record;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageTitle,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chatTitleLength,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds) ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : 0);\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\n\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [chatId]);\n\n // Modify index after unpinning\n useEffect(() => {\n setPinnedMessageIndex(pinnedMessagesCount ? cycleRestrict(pinnedMessagesCount, pinnedMessageIndex) : -1);\n }, [pinnedMessagesCount, pinnedMessageIndex]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = windowWidth >= MOBILE_SCREEN_MAX_WIDTH && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef(null);\n const shouldAnimateTools = useRef(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const handleBackClick = useCallback(() => {\n if (IS_MOBILE_SCREEN) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread') {\n if (IS_MOBILE_SCREEN) {\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n let isActive = false;\n\n const totalCount = Object.values(chatsById).reduce((total, chat) => {\n if (isChatArchived(chat)) {\n return total;\n }\n\n const count = chat.unreadCount || 0;\n if (count && (!chat.isMuted || chat.unreadMentionsCount)) {\n isActive = true;\n }\n\n return total + count;\n }, 0);\n\n if (!totalCount) {\n return undefined;\n }\n\n return {\n isActive,\n totalCount,\n };\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(pinnedMessage && !shouldRenderAudioPlayer);\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const lang = useLang();\n\n function renderInfo() {\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

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

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

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

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

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

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n
\n {isChatPrivate(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n
\n \n
\n \n {unreadCountInfo && (\n
\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n
\n )}\n
\n );\n }\n\n return (\n
\n \n {renderInfo}\n \n\n
\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n \n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n const originChat = selectThreadOriginChat(global, chatId, threadId);\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds && pinnedIds.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds && scheduledIds.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (threadInfo) {\n messagesCount = threadInfo.messagesCount;\n }\n }\n\n let state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chatTitleLength: chat && getChatTitle(chat).length,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType === 'thread' && messagesById) {\n if (threadId === MAIN_THREAD_ID) {\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n\n if (pinnedMessageIds && pinnedMessageIds.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n state = {\n ...state,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n };\n }\n } else {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const sender = message ? selectForwardedSender(global, message) : undefined;\n const topMessageTitle = sender ? getSenderTitle(sender) : undefined;\n\n state = {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n messagesById,\n canUnpin: false,\n topMessageTitle,\n };\n }\n }\n\n return state;\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDatetime = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDatetime) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDatetime,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebounce(ms: number, shouldRunFirst?: boolean, shouldRunLast?: boolean) {\n return useMemo(() => {\n return debounce((cb) => cb(), ms, shouldRunFirst, shouldRunLast);\n }, [ms, shouldRunFirst, shouldRunLast]);\n}\n","import { MutableRefObject } from 'react';\nimport React, {\n FC, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { MESSAGE_LIST_SENSITIVE_AREA } from '../../config';\nimport resetScroll from '../../util/resetScroll';\nimport { useIntersectionObserver, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\n\ntype OwnProps = {\n containerRef: MutableRefObject;\n className: string;\n messageIds: number[];\n containerHeight?: number;\n listItemElementsRef: MutableRefObject;\n anchorIdRef: MutableRefObject;\n anchorTopRef: MutableRefObject;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n focusingId?: number;\n onFabToggle: AnyToVoidFunction;\n children: any;\n};\n\nconst FAB_THRESHOLD = 50;\nconst FAB_FREEZE_TIMEOUT = 100;\n\n// Local flag is used because `freeze/unfreeze` methods are controlled by heavy animation\nlet isFabFrozen = false;\n\nconst MessageScroll: FC = ({\n containerRef,\n className,\n messageIds,\n containerHeight,\n listItemElementsRef,\n focusingId,\n anchorIdRef,\n anchorTopRef,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n children,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef(null);\n\n const updateFabVisibility = useCallback(() => {\n if (isFabFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = scrollHeight - scrollTop - offsetHeight;\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom === 0;\n\n onFabToggle(firstUnreadId ? !isAtBottom : !isNearBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId]);\n\n const {\n observe: observeIntersection,\n freeze: freezeForLoadMore,\n unfreeze: unfreezeForLoadMore,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger' && (target as HTMLDivElement).dataset.isActive) {\n resetScroll(containerRef.current!);\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD,\n }, ([{ target }]) => {\n if ((target as HTMLDivElement).dataset.isActive) {\n updateFabVisibility();\n }\n });\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n // Do not load more and show FAB when focusing\n useOnChange(() => {\n if (focusingId) {\n freezeForLoadMore();\n freezeForFab();\n } else {\n unfreezeForFab();\n unfreezeForLoadMore();\n }\n }, [focusingId]);\n\n // Remember scroll position before updating height\n useOnChange(() => {\n if (!listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n }, [messageIds, containerHeight]);\n\n // Workaround for FAB flickering with tall incoming message\n useOnChange(() => {\n isFabFrozen = true;\n\n setTimeout(() => {\n isFabFrozen = false;\n }, FAB_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n // Workaround for stuck FAB when many unread messages\n useEffect(updateFabVisibility, [firstUnreadId]);\n\n return (\n
\n
\n {children}\n \n \n
\n );\n};\n\nexport default MessageScroll;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMediaWithNoText = (photo || video) && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video && video.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean) {\n return hasText ? MIN_MEDIA_WIDTH_WITH_TEXT : MIN_MEDIA_WIDTH;\n}\n\nexport function calculateMediaDimensions(message: ApiMessage) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto)\n : calculateVideoDimensions(video!, isOwn, isForwarded);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage } from '../../../../api/types';\nimport { IDimensions } from '../../../../modules/helpers';\n\nimport { MOBILE_SCREEN_MAX_WIDTH } from '../../../../config';\nimport { REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nconst MAX_WIDTH_MOBILE_VW = 69;\nconst MAX_WIDTH_DESK_OWN_REM = 30;\nconst MAX_WIDTH_DESK_REM = 29;\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: IDimensions;\n};\n\nfunction getMaxWidth(isOwn: boolean, isForwarded: boolean, windowWidth: number) {\n if (windowWidth <= MOBILE_SCREEN_MAX_WIDTH) {\n return (windowWidth / 100) * MAX_WIDTH_MOBILE_VW - (isForwarded ? 1.625 : 0) * REM;\n }\n\n const maxWidth = isOwn ? MAX_WIDTH_DESK_OWN_REM : MAX_WIDTH_DESK_REM;\n\n return (maxWidth - (isForwarded ? 1.625 : 0)) * REM;\n}\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as IDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: IDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n album: IAlbum,\n windowWidth: number,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getMaxWidth(isOwn, isForwarded, windowWidth);\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","let element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n element.style.font = '400 12px Roboto, \"Helvetica Neue\", \"Apple Color Emoji\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\nimport { FocusDirection } from '../../../../types';\n\n// This is the max scroll offset within existing viewport.\nconst FOCUS_MAX_OFFSET = 1500;\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: number,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'center',\n FOCUS_MARGIN,\n focusDirection === undefined ? FOCUS_MAX_OFFSET : RELOCATED_FOCUS_OFFSET,\n focusDirection,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? : undefined;\n};\n\nexport default ContextMenuContainerAsync;\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n targetUser?: ApiUser;\n targetMessage?: ApiMessage;\n targetChatId?: number;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const content = renderActionMessageText(\n message,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const userId = message.senderId;\n const { targetUserId, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n sender,\n ...(targetUserId && { targetUser: selectUser(global, targetUserId) }),\n targetChatId,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n\n useLang();\n\n const senderTitle = sender && getSenderTitle(sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl)}\n
\n
{renderText(senderTitle || title || NBSP)}
\n

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

\n
\n
\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: () => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default MessageMeta;\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(isMediaReady, 'slow');\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && shouldRenderFullMedia && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { LAYERS_TRANSITION_DURATION } from '../../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useBlur from '../../../../hooks/useBlur';\n\nexport default function useBlurredMediaThumb(message: ApiMessage, fullMediaData?: string) {\n return useBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN ? LAYERS_TRANSITION_DURATION : undefined,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = 'rgba(255,255,255,1)';\n\nexport default async (src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean) => {\n return isSelected ? SELECTED_APPENDIX_BACKGROUND : getAppendixColorFromImage(src, isOwn);\n};\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n shouldAffectAppendix,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = isDownloadAllowed && isIntersecting;\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, size), !shouldDownload);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbDataUri = useBlurredMediaThumb(message, fullMediaData);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, shouldDownload && !fullMediaData);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled, 'slow');\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(fullMediaData, 'slow');\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const thumbClassName = buildClassName(\n 'thumbnail',\n !thumbDataUri && 'empty',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!fullMediaData && !isDownloadAllowed && (\n \n )}\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n
\n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n canMessagePlayVideoInline,\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n\n const video = message.content.video!;\n const localBlobUrl = video.blobUrl;\n const canPlayInline = Boolean(localBlobUrl) || canMessagePlayVideoInline(video);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(shouldAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, previewBlobUrl);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const previewMediaData = previewBlobUrl || thumbDataUri;\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(canPlayInline && isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && (canPlayInline && !isBuffered),\n );\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(fullMediaData, 'slow');\n\n const [playProgress, setPlayProgress] = useState(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded);\n\n useHeavyAnimationCheckForVideo(videoRef, isInline);\n\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (canPlayInline && !fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (canPlayInline && fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, canPlayInline, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const thumbClassName = buildClassName('thumbnail', !previewMediaData && 'empty');\n const videoClassName = buildClassName('full-media', transitionClassNames);\n const videoStyle = previewMediaData ? `background-image: url(${previewMediaData}); background-size: cover` : '';\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n const shouldRenderInlineVideo = isInline;\n const shouldRenderHqPreview = !canPlayInline && mediaData;\n const shouldRenderPlayButton = !canPlayInline || (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = canPlayInline && !isDownloadAllowed;\n\n return (\n \n {(shouldRenderThumb || !isInline) && (\n \n )}\n {shouldRenderInlineVideo && (\n \n \n \n )}\n {shouldRenderHqPreview && (\n \n )}\n {shouldRenderPlayButton && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && (\n \n )}\n {isTransferring && !canPlayInline ? (\n {Math.round(transferProgress * 100)}%\n ) : isTransferring && canPlayInline ? (\n ...\n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(video.duration - playProgress)}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst Contact: FC = ({\n contact, user, openUserInfo,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n return {\n user: selectUser(global, contact.userId),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, memo, useState,\n} from '../../lib/teact/teact';\n\nimport Checkbox from './Checkbox';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n};\n\ntype OwnProps = {\n id?: string;\n options: IRadioOption[];\n selected?: string[];\n disabled?: boolean;\n round?: boolean;\n loadingOptions?: string[];\n onChange: (value: string[]) => void;\n};\n\nconst CheckboxGroup: FC = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState([]);\n\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value, checked } = event.currentTarget;\n let newValues: string[];\n if (checked) {\n newValues = [...values, value];\n } else {\n newValues = values.filter((v) => v !== value);\n }\n\n setValues(newValues);\n onChange(newValues);\n }, [onChange, values]);\n\n return (\n
\n {options.map((option) => (\n \n ))}\n
\n );\n};\n\nexport default memo(CheckboxGroup);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result && result.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n \n \n `;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n
\n
\n {answerPercent}%\n {showIcon && (\n \n \n \n )}\n
\n
\n
\n {renderText(answer.text)}\n
\n
\n
\n \n
\n
\n
\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n loadMessage,\n onSendVote,\n openPollResults,\n}) => {\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [chosenOptions, setChosenOptions] = useState([]);\n const [isSolutionShown, setIsSolutionShown] = useState(false);\n const [wasSubmitted, setWasSubmitted] = useState(false);\n const [closePeriod, setClosePeriod] = useState(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000), summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${formatMediaDuration(closePeriod)}\n \n \n `;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n \n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n
\n {recentVoters.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n \n )\n );\n }\n\n return (\n
\n {renderSolution()}\n
{renderText(summary.question)}
\n
\n {getPollTypeString(summary)}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote &&
}\n {summary.quiz && poll.results.solution && !canVote && (\n \n \n \n )}\n
\n {canVote && (\n
\n {isMultiple\n ? (\n \n )\n : (\n \n )}\n
\n )}\n {!canVote && (\n
\n {summary.answers.map(renderResultOption)}\n
\n )}\n {!canViewResult && !isMultiple && (\n
{getReadableVotersCount(summary.quiz, results.totalVoters)}
\n )}\n {isMultiple && (\n \n {lang('PollSubmitVotes')}\n \n )}\n {canViewResult && (\n \n {lang('PollViewResults')}\n \n )}\n
\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'Quiz' : 'Anonymous Quiz';\n }\n\n if (summary.closed) {\n return 'Final results';\n }\n\n return summary.isPublic ? 'Poll' : 'Anonymous Poll';\n}\n\nfunction getReadableVotersCount(isQuiz: true | undefined, count?: number) {\n if (!count) {\n return isQuiz ? 'No answers yet' : 'No voters yet';\n }\n\n return isQuiz ? `${count} answered` : `${count} voted`;\n}\n\nexport default memo(withGlobal(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { byId: usersById } = global.users;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n inPreview?: boolean;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n inPreview,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n if (webPage && (isSquarePhoto || webPage.hasDocument)) {\n window.open(webPage.url);\n } else if (onMediaClick) {\n onMediaClick();\n }\n }, [webPage, isSquarePhoto, onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = webPage;\n\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n );\n\n return (\n \n {photo && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

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

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

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

{renderText(title)}

\n )}\n {text && (\n

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

\n )}\n
\n {photoUrl && (\n \n )}\n {description && (\n

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

\n )}\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nexport default function withSelectControl(WrapedComponent: FC) {\n const Component: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(Component));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n};\n\ntype DispatchProps = Pick;\n\nconst Album: FC = ({\n album,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n cancelSendingMessage,\n}) => {\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload ? fileUpload.progress : undefined;\n const { dimensions, sides } = albumLayout.layout[index];\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom)\n );\n\n return (\n \n );\n } else if (video) {\n return (\n \n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n \n {album.messages.map(renderAlbumMessage)}\n \n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n return {\n uploadsById: global.fileUploads.byMessageLocalId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport buildClassName from '../../../util/buildClassName';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport safePlay from '../../../util/safePlay';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n lastSyncTime?: number;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad && shouldAutoPlay);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = isDownloadAllowed && !isBuffered;\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n const [isActivated, setIsActivated] = useState(false);\n const [progress, setProgress] = useState(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const circumference = 94 * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `\n \n `;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n requestAnimationFrame(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n } else {\n playerEl.pause();\n }\n } else {\n playerEl.currentTime = 0;\n setIsActivated(true);\n capturePlaying();\n }\n }, [capturePlaying, isActivated, mediaData]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n \n {shouldRenderThumb && (\n
\n \n
\n )}\n {mediaData && (\n
\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n \n \n
\n )}\n
\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {!mediaData && !isDownloadAllowed && (\n \n )}\n
\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && }\n
\n
\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC = ({ message, onClick }) => {\n return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {button.text}\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../../modules/helpers';\nimport { formatInteger, formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst CommentButton: FC = ({\n disabled, threadInfo, usersById, chatsById, openChat,\n}) => {\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isChatPrivate(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n
\n {recentRepliers.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n \n \n {(!recentRepliers || recentRepliers.length === 0) && }\n {renderRecentRepliers()}\n
{renderLabel(messagesCount)}
\n \n \n );\n};\n\nfunction renderLabel(messagesCount: number) {\n if (messagesCount === 0) {\n return 'Leave a Comment';\n }\n\n if (messagesCount === 1) {\n return '1 Comment';\n }\n\n return `${formatInteger(messagesCount)} Comments`;\n}\n\nexport default memo(withGlobal(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { FocusDirection, IAlbum, MediaViewerOrigin } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectShouldAutoLoadMedia,\n selectShouldAutoPlayMedia, selectShouldLoopStickers,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji, getSenderTitle, getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentsButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n forceSenderName?: boolean;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isChannel?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n shouldAutoLoadMedia?: boolean;\n shouldAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '';\nconst APPEARANCE_DELAY = 10;\n\nconst Message: FC = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n shouldAutoLoadMedia,\n shouldAutoPlayMedia,\n shouldLoopStickers,\n focusMessage,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n openChat,\n cancelSendingMessage,\n markMessagesRead,\n sendPollVote,\n toggleMessageSelection,\n setReplyingToId,\n openForwardMenu,\n clickInlineButton,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const { width: windowWidth } = useWindowSize();\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { chatId, id: messageId, threadInfo } = message;\n\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const { forwardInfo, viaBotId } = message;\n const asForwarded = forwardInfo && !isChatWithSelf && !forwardInfo.isLinkedChannelPost;\n const isInDocumentGroup = !!message.groupedId && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n });\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n\n useEnsureMessage(chatId, hasReply ? message.replyToMessageId : undefined, replyMessage, message.id);\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn]);\n\n const handleGroupDocumentMessagesSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n\n toggleMessageSelection({\n messageId,\n groupedId: message.groupedId,\n });\n }, [messageId, message.groupedId, toggleMessageSelection]);\n\n const handleMessageSelect = useCallback((e?: ReactMouseEvent) => {\n const params = isAlbum && album && album.messages\n ? {\n messageId,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: e && e.shiftKey,\n }\n : { messageId, withShift: e && e.shiftKey };\n toggleMessageSelection(params);\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n }, []);\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isChatPrivate(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n return;\n }\n\n if (isChatPrivate(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({ chatId, threadId, messageId: message.replyToMessageId });\n }, [focusMessage, chatId, threadId, message.replyToMessageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId: message.groupedId });\n }, [openForwardMenu, chatId, message.groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId: message.groupedId, groupedChatId: chatId,\n });\n return;\n }\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }, [focusMessage, forwardInfo, message, chatId, isInDocumentGroup]);\n\n const lang = useLang();\n\n let style = '';\n let calculatedWidth;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), album!, windowWidth) : undefined;\n }, [isAlbum, windowWidth, isOwn, asForwarded, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), width);\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), albumLayout.containerStyle.width);\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id);\n const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined;\n const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined;\n const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts &&

{textParts}

}\n {webPage && (\n \n )}\n {invoice && (\n \n )}\n
\n );\n }\n\n function renderSenderName() {\n const shouldRender = !customShape && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer) {\n senderTitle = getSenderTitle(senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo && forwardInfo.hiddenUserName) {\n senderTitle = forwardInfo.hiddenUserName;\n }\n\n return (\n
\n {senderTitle ? (\n \n {renderText(senderTitle)}\n \n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n {lang('ViaBot')}\n \n {renderText(`@${botSender.username}`)}\n \n \n )}\n {forwardInfo && forwardInfo.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = canShowActionButton && isChannel && !isScheduled;\n const canFocus = canShowActionButton && (\n (forwardInfo && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn)) && forwardInfo.fromMessageId)\n || isPinnedList\n );\n const showCommentsButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n\n return (\n \n \n {!isInDocumentGroup && (\n
\n {isSelected && }\n
\n )}\n {isLastInDocumentGroup && (\n \n {isGroupSelected && (\n \n )}\n \n )}\n {withAvatar && renderAvatar()}\n \n \n {contentClassName.includes('has-appendix') && (
)}\n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && (\n \n )}\n {canForward ? (\n \n \n \n ) : canFocus ? (\n \n \n \n ) : undefined}\n {showCommentsButton && }\n
\n {message.inlineButtons && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToMessageId, isOutgoing,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isChannel = chat && isChatChannel(chat);\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = canShowSender ? selectSender(global, message) : undefined;\n const originSender = selectForwardedSender(global, message);\n const botSender = viaBotId ? selectUser(global, viaBotId) : undefined;\n\n const threadTopMessageId = threadId ? selectThreadTopMessageId(global, chatId, threadId) : undefined;\n const isThreadTop = message.id === threadTopMessageId;\n\n const shouldHideReply = replyToMessageId === threadTopMessageId;\n const replyMessage = replyToMessageId && !shouldHideReply\n ? selectChatMessage(global, chatId, replyToMessageId)\n : undefined;\n const replyMessageSender = replyMessage && selectSender(global, replyMessage);\n\n const uploadProgress = selectUploadProgress(global, message);\n const isFocused = messageListType === 'thread' && (\n album\n ? album.messages.some((m) => selectIsMessageFocused(global, m))\n : selectIsMessageFocused(global, message)\n );\n\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && focusedMessage) || {};\n\n const isForwarding = forwardMessages.messageIds && forwardMessages.messageIds.includes(id);\n\n const { query: highlight } = selectCurrentTextSearch(global) || {};\n\n const singleEmoji = getMessageSingleEmoji(message);\n let isSelected: boolean;\n\n if (album && album.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n return {\n forceSenderName,\n sender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isPinnedList: messageListType === 'pinned',\n shouldAutoLoadMedia: chat ? selectShouldAutoLoadMedia(global, message, chat, sender) : undefined,\n shouldAutoPlayMedia: selectShouldAutoPlayMedia(global, message),\n shouldLoopStickers: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'cancelSendingMessage',\n 'openUserInfo',\n 'openChat',\n 'markMessagesRead',\n 'sendPollVote',\n 'toggleMessageSelection',\n 'setReplyingToId',\n 'openForwardMenu',\n 'clickInlineButton',\n ]),\n)(Message));\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, MESSAGE_LIST_SLICE, SCHEDULED_WHEN_ONLINE } from '../../config';\nimport { IS_ANDROID, IS_IOS, IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages, selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n getMessageOriginalId,\n isActionMessage,\n isChatChannel,\n isChatPrivate,\n isOwnMessage,\n getCanPostInChat,\n} from '../../modules/helpers';\nimport {\n compact,\n flatten,\n orderBy,\n pick,\n} from '../../util/iteratees';\nimport {\n fastRaf, debounce, throttleWithTickEnd, onTickEnd,\n} from '../../util/schedulers';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages, MessageDateGroup, isAlbum } from './helpers/groupMessages';\nimport { ObserveFn, useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\nimport MessageScroll from './MessageScroll';\nimport Message from './message/Message';\nimport ActionMessage from './ActionMessage';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n type: MessageListType;\n onFabToggle: (show: boolean) => void;\n hasTools?: boolean;\n bottomOffset: 'none' | 'small' | 'big';\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n canPost?: boolean;\n isChatWithSelf?: boolean;\n messageIds?: number[];\n messagesById?: Record;\n firstUnreadId?: number;\n isViewportNewest?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n focusingId?: number;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n lastMessage?: ApiMessage;\n botDescription?: string;\n threadTopMessageId?: number;\n threadFirstMessageId?: number;\n hasLinkedChat?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst BOTTOM_THRESHOLD = 100;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_MOBILE_SCREEN ? 300 : 500;\nconst FOCUSING_DURATION = 1000;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst FOCUSING_FADE_ANIMATION_DURATION = 200;\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst runDebouncedForScroll = debounce((cb) => cb(), SCROLL_DEBOUNCE, false);\nconst runThrottledOnTickEnd = throttleWithTickEnd((cb) => cb());\n\nconst MessageList: FC = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n isChatLoaded,\n isChannelChat,\n canPost,\n bottomOffset,\n isChatWithSelf,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n animationLevel,\n loadViewportMessages,\n markMessageListRead,\n markMessagesRead,\n setScrollOffset,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n // We update local cached `scrollOffsetRef` when opening chat.\n // Then we update global version every second on scrolling.\n const scrollOffsetRef = useRef((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef();\n const anchorTopRef = useRef();\n const listItemElementsRef = useRef();\n // Updated when opening chat (to preserve divider even after messages are read)\n const memoUnreadDividerBeforeIdRef = useRef(firstUnreadId);\n // Updated every time (to be used from intersection callback closure)\n const memoFirstUnreadIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(!messageIds);\n\n const [containerHeight, setContainerHeight] = useState();\n const [hasFocusing, setHasFocusing] = useState(Boolean(focusingId));\n\n const areMessagesLoaded = Boolean(messageIds);\n useOnChange(() => {\n // We only need it first time when message list appears\n if (areMessagesLoaded) {\n onTickEnd(() => {\n shouldAnimateAppearanceRef.current = false;\n });\n }\n }, [areMessagesLoaded]);\n\n useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n }, [firstUnreadId]);\n\n const {\n observe: observeIntersectionForMedia, freeze: freezeForMedia, unfreeze: unfreezeForMedia,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n margin: INTERSECTION_MARGIN_FOR_MEDIA,\n });\n\n const {\n observe: observeIntersectionForReading, freeze: freezeForReading, unfreeze: unfreezeForReading,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, (entries) => {\n if (type !== 'thread') {\n return;\n }\n\n let maxId = 0;\n const mentionIds: number[] = [];\n\n entries.forEach((entry) => {\n const { isIntersecting, target } = entry;\n\n if (!isIntersecting) {\n return;\n }\n\n const { dataset } = target as HTMLDivElement;\n\n const messageId = Number(dataset.lastMessageId || dataset.messageId);\n if (messageId > maxId) {\n maxId = messageId;\n }\n\n if (dataset.hasUnreadMention) {\n mentionIds.push(messageId);\n }\n });\n\n if (memoFirstUnreadIdRef.current && maxId >= memoFirstUnreadIdRef.current) {\n markMessageListRead({ maxId });\n }\n\n if (mentionIds.length) {\n markMessagesRead({ messageIds: mentionIds });\n }\n });\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n\n if (focusingId) {\n freezeForMedia();\n freezeForReading();\n } else {\n unfreezeForReading();\n unfreezeForMedia();\n }\n }, [focusingId]);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n useEffect(() => {\n if (focusingId) {\n setHasFocusing(true);\n } else {\n setTimeout(() => {\n setHasFocusing(false);\n }, FOCUSING_FADE_ANIMATION_DURATION);\n }\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const [loadMoreBackwards, loadMoreForwards, loadMoreAround] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\n fastRaf(() => {\n if (!container.parentElement) {\n return;\n }\n\n scrollOffsetRef.current = container.scrollHeight - container.scrollTop;\n\n if (type === 'thread') {\n setScrollOffset({ chatId, threadId, scrollOffset: scrollOffsetRef.current });\n }\n });\n });\n }, [updateStickyDates, hasTools, type, setScrollOffset, chatId, threadId]);\n\n // Container resize observer (caused by Composer reply/webpage panels)\n useEffect(() => {\n if (!('ResizeObserver' in window) || process.env.APP_ENV === 'perf') {\n return undefined;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n // During animation\n if (!(entry.target as HTMLDivElement).offsetParent) {\n return;\n }\n\n setContainerHeight(entry.contentRect.height);\n });\n\n observer.observe(containerRef.current!);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n useLayoutEffect(() => {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, []);\n\n // Workaround for an iOS bug when animated stickers sometimes disappear\n useLayoutEffect(() => {\n if (!IS_IOS) {\n return;\n }\n\n runThrottledOnTickEnd(() => {\n if (!(containerRef.current as HTMLDivElement).querySelector('.AnimatedSticker.is-playing')) {\n return;\n }\n\n const style = (containerRef.current as HTMLDivElement).style as any;\n style.webkitOverflowScrolling = style.webkitOverflowScrolling === 'auto' ? '' : 'auto';\n });\n });\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll('.message-list-item'));\n\n // During animation\n if (!container.offsetParent) {\n return;\n }\n\n // Add extra height when few messages to allow smooth scroll animation. Uses assumption that `parentElement`\n // is a Transition slide and its CSS class can not be reset in a declarative way.\n const shouldForceScroll = (\n isViewportNewest\n && (messageIds && messageIds.length < MESSAGE_LIST_SLICE / 2)\n && !container.parentElement!.classList.contains('force-messages-scroll')\n && (container.firstElementChild as HTMLDivElement)!.clientHeight <= container.offsetHeight * 2\n );\n\n if (shouldForceScroll) {\n container.parentElement!.classList.add('force-messages-scroll');\n\n setTimeout(() => {\n if (container.parentElement) {\n container.parentElement.classList.remove('force-messages-scroll');\n }\n }, FOCUSING_DURATION);\n }\n\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const scrollOffset = scrollOffsetRef.current!;\n const lastItemElement = listItemElementsRef.current[listItemElementsRef.current.length - 1];\n\n // If two messages come at once (e.g. via Quiz Bot) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes.\n // To workaround that, we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n const isAtBottom = isViewportNewest && prevIsViewportNewest && (\n scrollOffset - (prevContainerHeight || offsetHeight) - lastItemHeight <= BOTTOM_THRESHOLD\n );\n\n let newScrollTop!: number;\n\n const hasFirstMessageChanged = messageIds && prevMessageIds && messageIds[0] !== prevMessageIds[0];\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n\n if (isAtBottom && hasLastMessageChanged && !hasFirstMessageChanged && !memoFocusingIdRef.current) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n undefined,\n undefined,\n undefined,\n true,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n // Scroll still needs to be restored after container resize\n if (!shouldForceScroll) {\n return;\n }\n }\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.time('scrollTop');\n }\n\n const isResized = prevContainerHeight !== undefined && prevContainerHeight !== containerHeight;\n const anchor = anchorIdRef.current && container.querySelector(`#${anchorIdRef.current}`);\n const unreadDivider = (\n !anchor\n && memoUnreadDividerBeforeIdRef.current\n && container.querySelector(`.${UNREAD_DIVIDER_CLASS}`)\n );\n\n if (isAtBottom && isResized) {\n if (isAnimatingScroll()) {\n return;\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n } else if (anchor) {\n const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP);\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, newScrollTop);\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffect(() => {\n if (!animationLevel || animationLevel > 0) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isChatPrivate(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf);\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n !withUsers && 'no-avatars',\n isChannelChat && 'no-avatars',\n (!canPost || bottomOffset !== 'none') && 'bottom-padding',\n (bottomOffset !== 'none') && `bottom-padding-${bottomOffset}`,\n isSelectModeActive && 'select-mode-active',\n hasFocusing && 'has-focusing',\n isScrolled && 'scrolled',\n );\n\n return (\n
\n {isRestricted ? (\n
\n \n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n \n
\n ) : botDescription ? (\n
{renderText(lang(botDescription), ['br', 'emoji', 'links'])}
\n ) : messageIds && !messageGroups ? (\n
{lang('NoMessages')}
\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n {renderMessages(\n lang,\n messageGroups || groupMessages([lastMessage!]),\n observeIntersectionForReading,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n withUsers,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n threadId,\n type,\n threadTopMessageId,\n threadFirstMessageId,\n hasLinkedChat,\n messageGroups ? type === 'scheduled' : false,\n !messageGroups || !shouldAnimateAppearanceRef.current,\n )}\n \n ) : (\n \n )}\n
\n );\n};\n\nfunction renderMessages(\n lang: LangFn,\n messageGroups: MessageDateGroup[],\n observeIntersectionForReading: ObserveFn,\n observeIntersectionForMedia: ObserveFn,\n observeIntersectionForAnimatedStickers: ObserveFn,\n withUsers: boolean,\n currentAnchorIdRef: { current: string | undefined },\n memoFirstUnreadIdRef: { current: number | undefined },\n threadId: number,\n type: MessageListType,\n threadTopMessageId?: number,\n threadFirstMessageId?: number,\n hasLinkedChat?: boolean,\n isSchedule = false,\n noAppearanceAnimation = false,\n) {\n const unreadDivider = (\n
\n {lang('UnreadMessages')}\n
\n );\n\n const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {\n return acc + flatten(messageGroup.senderGroups).length;\n }, 0);\n let appearanceIndex = 0;\n\n const dateGroups = messageGroups.map((\n dateGroup: MessageDateGroup,\n dateGroupIndex: number,\n dateGroupsArray: MessageDateGroup[],\n ) => {\n const senderGroups = dateGroup.senderGroups.map((\n senderGroup,\n senderGroupIndex,\n senderGroupsArray,\n ) => {\n if (senderGroup.length === 1 && !isAlbum(senderGroup[0]) && isActionMessage(senderGroup[0])) {\n const message = senderGroup[0];\n\n return compact([\n message.id === memoFirstUnreadIdRef.current && unreadDivider,\n ,\n ]);\n }\n\n let currentDocumentGroupId: string | undefined;\n\n return flatten(senderGroup.map((\n messageOrAlbum,\n messageIndex,\n ) => {\n const message = isAlbum(messageOrAlbum) ? messageOrAlbum.mainMessage : messageOrAlbum;\n const album = isAlbum(messageOrAlbum) ? messageOrAlbum : undefined;\n const isOwn = isOwnMessage(message);\n const isMessageAlbum = isAlbum(messageOrAlbum);\n const nextMessage = senderGroup[messageIndex + 1];\n\n if (message.previousLocalId && currentAnchorIdRef.current === `message${message.previousLocalId}`) {\n currentAnchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const shouldRenderUnreadDivider = (\n (message.id === memoFirstUnreadIdRef.current && memoFirstUnreadIdRef.current !== threadFirstMessageId)\n || (message.id === threadTopMessageId && memoFirstUnreadIdRef.current === threadFirstMessageId)\n );\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n shouldRenderUnreadDivider && unreadDivider,\n ,\n message.id === threadTopMessageId && (\n
\n {lang('DiscussionStarted')}\n
\n ),\n ]);\n }));\n });\n\n return (\n \n
\n \n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(dateGroup.datetime)}\n \n
\n {flatten(senderGroups)}\n \n );\n });\n\n return flatten(dateGroups);\n}\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, type }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const messageIds = selectCurrentMessageIds(global, chatId, threadId, type);\n const messagesById = type === 'scheduled'\n ? selectScheduledMessages(global, chatId)\n : selectChatMessages(global, chatId);\n const threadTopMessageId = selectThreadTopMessageId(global, chatId, threadId);\n\n if (\n threadId !== MAIN_THREAD_ID\n && !(messagesById && threadTopMessageId && messagesById[threadTopMessageId])\n ) {\n return {};\n }\n\n const { isRestricted, restrictionReason, lastMessage } = chat;\n const focusingId = selectFocusedMessageId(global, chatId);\n\n const withLastMessageWhenPreloading = (\n threadId === MAIN_THREAD_ID\n && !messageIds && !chat.unreadCount && !focusingId && lastMessage && !lastMessage.groupedId\n );\n\n let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n const chatBot = selectChatBot(global, chatId)!;\n if (chatBot.fullInfo) {\n botDescription = chatBot.fullInfo.botDescription || 'NoMessages';\n } else {\n botDescription = 'Updating bot info...';\n }\n }\n\n return {\n isChatLoaded: true,\n isRestricted,\n restrictionReason,\n isChannelChat: isChatChannel(chat),\n canPost: getCanPostInChat(chat, threadId),\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n messageIds,\n messagesById,\n firstUnreadId: selectFirstUnreadId(global, chatId, threadId),\n isViewportNewest: type !== 'thread' || selectIsViewportNewest(global, chatId, threadId),\n threadFirstMessageId: selectFirstMessageId(global, chatId, threadId),\n focusingId,\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadViewportMessages',\n 'markMessageListRead',\n 'markMessagesRead',\n 'setScrollOffset',\n ]),\n)(MessageList));\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { getCanPostInChat } from '../../modules/helpers';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\n canPost?: boolean;\n unreadCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\n isShown,\n messageListType,\n canPost,\n unreadCount,\n focusLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const elementRef = useRef(null);\n\n const handleClick = useCallback(() => {\n if (!isShown) {\n return;\n }\n\n if (messageListType === 'thread') {\n focusLastMessage();\n } else {\n const messagesContainer = elementRef.current!.parentElement!.querySelector('.MessageList')!;\n const messsageElements = messagesContainer.querySelectorAll('.message-list-item');\n const lastMessageElement = messsageElements[messsageElements.length - 1];\n if (!lastMessageElement) {\n return;\n }\n\n fastSmoothScroll(messagesContainer, lastMessageElement, 'end', FOCUS_MARGIN);\n }\n }, [isShown, messageListType, focusLastMessage]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\n );\n\n return (\n
\n
\n \n \n \n {Boolean(unreadCount) && (\n
{formatIntegerCompact(unreadCount!)}
\n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return {};\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const canPost = chat && getCanPostInChat(chat, threadId);\n\n return {\n messageListType,\n canPost,\n unreadCount: chat && threadId === MAIN_THREAD_ID && messageListType === 'thread' ? chat.unreadCount : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusLastMessage']),\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { preloadImage, preloadVideo, createPosterForVideo } from '../../../../util/files';\n\nconst MAX_QUICK_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\nconst MAX_QUICK_IMG_SIZE = 1280; // px\n\nexport default async function buildAttachment(\n filename: string, blob: Blob, isQuick: boolean, options?: Partial,\n): Promise {\n const blobUrl = URL.createObjectURL(blob);\n const { type: mimeType, size } = blob;\n let quick;\n let previewBlobUrl;\n\n if (mimeType.startsWith('image/')) {\n if (isQuick) {\n const img = await preloadImage(blobUrl);\n const { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE || mimeType !== 'image/jpeg') {\n const newBlob = await squeezeImage(img);\n if (newBlob) {\n URL.revokeObjectURL(blobUrl);\n return buildAttachment(filename, newBlob, true, options);\n } else {\n return buildAttachment(filename, blob, false, options);\n }\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (mimeType.startsWith('video/')) {\n // Videos < 10 MB are always sent in quick mode (in other clients).\n // Quick mode for videos > 10 MB is not supported until client-side video squeezing is implemented.\n if (size < MAX_QUICK_VIDEO_SIZE) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n }\n\n previewBlobUrl = await createPosterForVideo(blobUrl);\n }\n\n return {\n blobUrl,\n filename,\n mimeType,\n size,\n quick,\n previewBlobUrl,\n ...options,\n };\n}\n\nfunction squeezeImage(img: HTMLImageElement): Promise {\n return new Promise((resolve) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n let { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE) {\n if (width >= height) {\n height *= MAX_QUICK_IMG_SIZE / width;\n width = MAX_QUICK_IMG_SIZE;\n } else {\n width *= MAX_QUICK_IMG_SIZE / height;\n height = MAX_QUICK_IMG_SIZE;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);\n canvas.toBlob(resolve, 'image/jpeg', 100);\n });\n}\n","export default __webpack_public_path__ + \"8ccc0b555efcec3616377aea078dda16.js\";","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface OpusRecorder extends Omit {\n new(options: AnyLiteral): OpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: OpusRecorder }>;\nlet OpusRecorder: OpusRecorder;\nlet mediaRecorder: OpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: OpusRecorder, cb: Function) {\n const source = recorder.sourceNode;\n const analyser = source.context.createAnalyser();\n analyser.fftSize = FFT_SIZE;\n source.connect(analyser);\n\n const dataLength = analyser.frequencyBinCount;\n const dataArray = new Uint8Array(dataLength);\n let isDestroyed = false;\n\n function tick() {\n if (isDestroyed) {\n return;\n }\n\n analyser.getByteFrequencyData(dataArray);\n\n const sum = dataArray.reduce((acc, current) => acc + current, 0);\n const mean = (sum / dataLength);\n const volume = mean / 255;\n\n cb(volume < MIN_VOLUME ? 0 : volume);\n\n requestAnimationFrame(tick);\n }\n\n tick();\n\n return () => {\n isDestroyed = true;\n };\n}\n","import { StateHookSetter, useEffect } from '../../../../lib/teact/teact';\nimport { ApiAttachment, ApiMessage } from '../../../../api/types';\n\nimport buildAttachment from '../helpers/buildAttachment';\nimport { EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID } from '../../../../config';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string) => void,\n setAttachments: StateHookSetter,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && input.tagName === 'INPUT' && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items).find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type));\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n if (!file && !pastedText) {\n return;\n }\n\n e.preventDefault();\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { DRAFT_DEBOUNCE, EDITABLE_INPUT_ID } from '../../../../config';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport { debounce } from '../../../../util/schedulers';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: number | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: number,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n saveDraft: GlobalActions['saveDraft'],\n clearDraft: GlobalActions['clearDraft'],\n) => {\n const updateDraft = useCallback((draftChatId: number, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n // Subscribe and handle `window.blur`\n useEffect(() => {\n function handleBlur() {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }\n\n window.addEventListener('blur', handleBlur);\n\n return () => {\n window.removeEventListener('blur', handleBlur);\n };\n }, [chatId, threadId, updateDraft]);\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? : undefined;\n};\n\nexport default DeleteMessageModalAsync;\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n \n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? : undefined;\n};\n\nexport default AttachMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? : undefined;\n};\n\nexport default SymbolMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const MentionMenu = useModuleLoader(Bundles.Extra, 'MentionMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionMenu ? : undefined;\n};\n\nexport default MentionMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? : undefined;\n};\n\nexport default CustomSendMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './EmojiTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst EmojiTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const EmojiTooltip = useModuleLoader(Bundles.Extra, 'EmojiTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return EmojiTooltip ? : undefined;\n};\n\nexport default EmojiTooltipAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotKeyboardMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotKeyboardMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const BotKeyboardMenu = useModuleLoader(Bundles.Extra, 'BotKeyboardMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotKeyboardMenu ? : undefined;\n};\n\nexport default BotKeyboardMenuAsync;\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isChatPrivate } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n}) => {\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isChatPrivate(fromChatId!) ? selectUser(global, fromChatId!) : selectChat(global, fromChatId!);\n }\n\n return {\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount: isForwarding ? forwardMessageIds!.length : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'focusMessage',\n 'exitForwardMode',\n ]),\n)(ComposerEmbeddedMessage));\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachmentModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachmentModalAsync: FC = (props) => {\n const { attachments } = props;\n const AttachmentModal = useModuleLoader(Bundles.Extra, 'AttachmentModal', !attachments.length);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachmentModal ? : undefined;\n};\n\nexport default AttachmentModalAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? : undefined;\n};\n\nexport default PollModalAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? : undefined;\n};\n\nexport default DropAreaAsync;\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevForAnimation from '../../../hooks/usePrevForAnimation';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n};\ntype DispatchProps = Pick;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n}) => {\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = usePrevForAnimation(webPagePreview);\n\n if (!shouldRender || !renderingWebPage) {\n return undefined;\n }\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = renderingWebPage;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId }): StateProps => {\n const noWebPage = selectNoWebPage(global, chatId, threadId);\n return {\n webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWebPagePreview', 'clearWebPagePreview', 'toggleMessageWebPage',\n ]),\n)(WebPagePreview));\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? : undefined;\n};\n\nexport default CalendarModalAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './PaymentModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst PaymentModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PaymentModal = useModuleLoader(Bundles.Extra, 'PaymentModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PaymentModal ? : undefined;\n};\n\nexport default PaymentModalAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './ReceiptModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReceiptModalAsync: FC = (props) => {\n const { isOpen } = props;\n const ReceiptModal = useModuleLoader(Bundles.Extra, 'ReceiptModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReceiptModal ? : undefined;\n};\n\nexport default ReceiptModalAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { EDITABLE_INPUT_ID, SCHEDULED_WHEN_ONLINE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED, IS_VOICE_RECORDING_SUPPORTED, IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n selectChat,\n selectIsChatWithBot,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatUser,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatGroup,\n isChatPrivate,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport useFlag from '../../../hooks/useFlag';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionMenu from './hooks/useMentionMenu';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport MentionMenu from './MentionMenu.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu.async';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport PaymentModal from '../../payment/PaymentModal.async';\nimport ReceiptModal from '../../payment/ReceiptModal.async';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps = {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n canSuggestMembers?: boolean;\n isPollModalOpen?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n botKeyboardMessageId?: number;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: number;\n usersById?: Record;\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst CAPTION_MAX_LENGTH = 1024;\nconst SENDING_ANIMATION_DURATION = 350;\n// eslint-disable-next-line max-len\nconst APPENDIX = '';\n\nconst Composer: FC = ({\n dropAreaState,\n shouldSchedule,\n canScheduleUntilOnline,\n onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n canSuggestMembers,\n isPollModalOpen,\n isPaymentModalOpen,\n isReceiptModalOpen,\n botKeyboardMessageId,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showError,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n closePaymentModal,\n openChat,\n clearReceipt,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n\n // Cache for frequently updated state\n const htmlRef = useRef(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID) {\n loadScheduledHistory();\n }\n }, [chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = useFlag();\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n const [isSymbolMenuLoaded, onSymbolMenuLoadingComplete] = useFlag();\n const [isHoverDisabled, disableHover, enableHover] = useFlag();\n\n const {\n startRecordingVoice,\n stopRecordingVoice,\n pauseRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef: mainButtonRef,\n startRecordTimeRef,\n } = useVoiceRecording();\n\n const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionMenuOpen, mentionFilter,\n closeMentionMenu, insertMention,\n mentionFilteredMembers,\n } = useMentionMenu(\n canSuggestMembers && !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isEmojiTooltipOpen, closeEmojiTooltip } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n const newHtml = renderText(text, ['escape_html', 'emoji_html', 'br_html'])\n .join('')\n .replace(/\\u200b+/g, '\\u200b');\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n if (IS_EMOJI_SUPPORTED) {\n // Insertion will trigger `onChange` in MessageInput, so no need to setHtml in state\n document.execCommand('insertText', false, text);\n } else {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n }\n\n return;\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n if (!IS_MOBILE_SCREEN) {\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }\n } else {\n setHtml(`${htmlRef.current!}${newHtml}`);\n }\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback(() => {\n setHtml('');\n setAttachments([]);\n closeEmojiTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionMenu();\n\n if (IS_MOBILE_SCREEN) {\n // @perf\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeEmojiTooltip, closeCalendar, closeMentionMenu, closeSymbolMenu]);\n\n // Handle chat change\n const prevChatId = usePrevious(chatId);\n useEffect(() => {\n if (!prevChatId || chatId === prevChatId) {\n return;\n }\n\n stopRecordingVoice();\n resetComposer();\n }, [chatId, prevChatId, resetComposer, stopRecordingVoice]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal, editMessage);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage, saveDraft, clearDraft);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n if (currentAttachments.length && text && text.length > CAPTION_MAX_LENGTH) {\n const extraLength = text.length - CAPTION_MAX_LENGTH;\n showError({\n error: {\n message: 'CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n },\n });\n return;\n }\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = Math.floor(Date.now() / 1000);\n const secondsSinceLastMessage = lastMessageSendTimeSeconds.current\n && Math.floor(nowSeconds - lastMessageSendTimeSeconds.current);\n const nextSendDateNotReached = slowMode.nextSendDate && slowMode.nextSendDate > nowSeconds;\n\n if (\n (secondsSinceLastMessage && secondsSinceLastMessage < slowMode.seconds)\n || nextSendDateNotReached\n ) {\n const secondsRemaining = nextSendDateNotReached\n ? slowMode.nextSendDate! - nowSeconds\n : slowMode.seconds - secondsSinceLastMessage!;\n showError({\n error: {\n message: `A wait of ${secondsRemaining} seconds is required before sending another message in this chat`,\n isSlowMode: true,\n },\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n messageInput.blur();\n\n return;\n }\n }\n\n sendMessage({\n text,\n entities,\n attachments: currentAttachments,\n scheduledAt,\n isSilent,\n });\n }\n if (isForwarding) {\n forwardMessages();\n }\n\n lastMessageSendTimeSeconds.current = Math.floor(Date.now() / 1000);\n\n clearDraft({ chatId, localOnly: true });\n\n // Wait until message animation starts\n requestAnimationFrame(resetComposer);\n }, [\n activeVoiceRecording, attachments, connectionState, chatId, slowMode, isForwarding, isAdmin,\n sendMessage, stopRecordingVoice, resetComposer, clearDraft, showError, forwardMessages,\n ]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(resetComposer);\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000));\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_MOBILE_SCREEN || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_MOBILE_SCREEN) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n handleSend();\n requestAnimationFrame(resetComposer);\n }\n break;\n case MainButtonState.Record:\n startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, resetComposer, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const lang = useLang();\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'Send message';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Posting media content is not allowed in this group.'\n : 'Record a voice message';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && (\n \n \n \n )}\n \n \n \n \n {renderedEditedMessage && (\n \n )}\n \n
\n
\n \n \n
\n {IS_MOBILE_SCREEN ? (\n \n \n \n \n \n ) : (\n \n \n \n )}\n \n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n {botKeyboardMessageId && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n\n return {\n editingMessage: selectEditingMessage(global, chatId, threadId, messageListType),\n connectionState: global.connectionState,\n draft: selectDraft(global, chatId, threadId),\n chat,\n isChatWithBot,\n isChatWithSelf,\n canScheduleUntilOnline: (\n !isChatWithSelf && !isChatWithBot\n && (chat && chatUser && isChatPrivate(chatId) && chatUser.status && Boolean(chatUser.status.wasOnline))\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds && scheduledIds.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId: messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined,\n isForwarding: chatId === global.forwardMessages.toChatId,\n canSuggestMembers: chat && isChatGroup(chat),\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat && chat.fullInfo && chat.fullInfo.members,\n currentUserId: global.currentUserId,\n usersById: global.users.byId,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n shouldSuggestStickers: global.settings.byKey.shouldSuggestStickers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showError',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'closePaymentModal',\n 'clearReceipt',\n 'loadScheduledHistory',\n 'openChat',\n ]),\n)(Composer));\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_IOS } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_IOS) {\n void voiceRecording.init();\n }\n }, []);\n\n const startRecordingVoice = useCallback(async () => {\n try {\n const { stop, pause } = await voiceRecording.start((tickVolume: number) => {\n if (recordButtonRef.current) {\n if (startRecordTimeRef.current && Date.now() % 4 === 0) {\n recordButtonRef.current.style.boxShadow = `0 0 0 ${(tickVolume || 0) * 50}px rgba(0,0,0,.15)`;\n }\n setCurrentRecordTime(Date.now());\n }\n });\n startRecordTimeRef.current = Date.now();\n setCurrentRecordTime(Date.now());\n\n setActiveVoiceRecording({ stop, pause });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }, []);\n\n const pauseRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\n\nexport default function useEmojiTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n) {\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(html) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({ emoji: html });\n } else if (hasStickers || !isSingleEmoji) {\n clearStickersForEmoji();\n }\n // We omit `hasStickers` here to prevent re-fetching after manually closing tooltip (via ).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [html, isSingleEmoji, clearStickersForEmoji, loadStickersForEmoji, isAllowed]);\n\n return {\n isEmojiTooltipOpen: hasStickers,\n closeEmojiTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection && selection.getRangeAt && selection.rangeCount) {\n const range = selection.getRangeAt(0);\n range.deleteContents();\n\n const fragment = range.createContextualFragment(html);\n const lastInsertedNode = fragment.lastChild;\n range.insertNode(fragment);\n if (lastInsertedNode) {\n range.setStartAfter(lastInsertedNode);\n range.setEndAfter(lastInsertedNode);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n}\n","export default function deleteLastCharacterOutsideSelection(html: string) {\n const tempInput = document.createElement('div');\n tempInput.contentEditable = 'true';\n tempInput.style.position = 'absolute';\n tempInput.style.left = '-10000px';\n tempInput.style.top = '-10000px';\n tempInput.innerHTML = html;\n document.body.appendChild(tempInput);\n let element = tempInput.lastChild!;\n\n if (element.lastChild) {\n // Selects the last and the deepest child of the element.\n while (element.lastChild) {\n element = element.lastChild;\n }\n }\n\n // Gets length of the element's content.\n const textLength = element.textContent!.length;\n const range = document.createRange();\n const selection = window.getSelection()!;\n\n // Sets selection position to the end of the element.\n range.setStart(element, textLength);\n range.setEnd(element, textLength);\n selection.removeAllRanges();\n selection.addRange(range);\n document.execCommand('delete', false);\n\n const result = tempInput.innerHTML;\n document.body.removeChild(tempInput);\n\n return result;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n editMessage: GlobalActions['editMessage'],\n) => {\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? : undefined;\n};\n\nexport default MobileSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? : undefined;\n};\n\nexport default MessageSelectToolbarAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? : undefined;\n};\n\nexport default UnpinAllMessagesModalAsync;\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n CONTENT_TYPES_FOR_QUICK_UPLOAD,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n} from '../../config';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV, MASK_IMAGE_ENABLED } from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n} from '../../modules/selectors';\nimport { getCanPostInChat, getMessageSendingRestrictionReason, isChatPrivate } from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevForAnimation from '../../hooks/usePrevForAnimation';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\nimport useLang from '../../hooks/useLang';\n\nimport Transition from '../ui/Transition';\nimport MiddleHeader from './MiddleHeader';\nimport MessageList from './MessageList';\nimport ScrollDownButton from './ScrollDownButton';\nimport Composer from './composer/Composer';\nimport Button from '../ui/Button';\nimport MobileSearch from './MobileSearch.async';\nimport MessageSelectToolbar from './MessageSelectToolbar.async';\nimport UnpinAllMessagesModal from '../common/UnpinAllMessagesModal.async';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n canPost?: boolean;\n messageSendingRestrictionReason?: string;\n hasPinnedOrAudioMessage?: boolean;\n customBackground?: string;\n patternColor?: string;\n isCustomBackgroundColor?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst CLOSE_ANIMATION_DURATION = IS_MOBILE_SCREEN ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction canBeQuicklyUploaded(item: DataTransferItem) {\n return item.kind === 'file' && item.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(item.type);\n}\n\nconst MiddleColumn: FC = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n canPost,\n messageSendingRestrictionReason,\n hasPinnedOrAudioMessage,\n customBackground,\n patternColor,\n isCustomBackgroundColor,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n animationLevel,\n openChat,\n unpinAllMessages,\n loadUser,\n}) => {\n const { width: windowWidth } = useWindowSize();\n\n const [dropAreaState, setDropAreaState] = useState(DropAreaState.None);\n const [isFabShown, setIsFabShown] = useState(false);\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\n\n const renderingChatId = usePrevForAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevForAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevForAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevForAnimation(canPost, CLOSE_ANIMATION_DURATION);\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useEffect(() => {\n setDropAreaState(DropAreaState.None);\n }, [chatId]);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items).every(canBeQuicklyUploaded);\n\n setDropAreaState(shouldDrawQuick ? DropAreaState.QuickFile : DropAreaState.Document);\n }, []);\n\n const handleHideDropArea = useCallback(() => {\n setDropAreaState(DropAreaState.None);\n }, []);\n\n const handleOpenUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(true);\n }, []);\n\n const closeUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(false);\n }, []);\n\n const handleUnpinAllMessages = useCallback(() => {\n unpinAllMessages({ chatId });\n closeUnpinModal();\n openChat({ id: chatId });\n }, [unpinAllMessages, openChat, closeUnpinModal, chatId]);\n\n const customBackgroundValue = useCustomBackground(customBackground);\n\n const hasTools = hasPinnedOrAudioMessage && (\n windowWidth < MOBILE_SCREEN_MAX_WIDTH\n || (\n isRightColumnShown && windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ) || (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n )\n );\n\n const className = buildClassName(\n hasTools && 'has-header-tools',\n customBackground && !isCustomBackgroundColor && 'custom-bg-image',\n customBackground && isCustomBackgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_ENABLED ? 'mask-image-enabled' : 'mask-image-disabled',\n );\n\n const messagingDisabledClassName = buildClassName(\n 'messaging-disabled',\n !isSelectModeActive && 'shown',\n );\n\n // CSS Variables calculation doesn't work properly with transforms, so we calculate transform values in JS\n const {\n composerHiddenScale, toolbarHiddenScale,\n composerTranslateX, toolbarTranslateX,\n unpinHiddenScale, toolbarForUnpinHiddenScale,\n } = useMemo(\n () => calculateMiddleFooterTransforms(windowWidth, renderingCanPost),\n [renderingCanPost, windowWidth],\n );\n\n const lang = useLang();\n\n return (\n \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.PanelHidePinnedMessages')}\n \n
\n )}\n {!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n \n
\n \n )}\n \n\n \n
\n {IS_MOBILE_SCREEN && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { isBackgroundBlurred, customBackground, patternColor } = global.settings.byKey;\n\n const isCustomBackgroundColor = Boolean((customBackground || '').match(/^#[a-f\\d]{6,8}$/i));\n const currentMessageList = selectCurrentMessageList(global);\n const { chats: { listIds } } = global;\n if (!currentMessageList || !listIds.active) {\n return {\n customBackground,\n isBackgroundBlurred,\n isCustomBackgroundColor,\n };\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const pinnedIds = selectPinnedIds(global, chatId);\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n\n const canPost = chat && getCanPostInChat(chat, threadId);\n const isBotNotStarted = selectIsChatBotNotStarted(global, chatId);\n const isPinnedMessageList = messageListType === 'pinned';\n\n return {\n chatId,\n threadId,\n messageListType,\n isPrivate: isChatPrivate(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && (!isBotNotStarted || IS_MOBILE_SCREEN),\n isPinnedMessageList,\n messageSendingRestrictionReason: chat && getMessageSendingRestrictionReason(chat),\n hasPinnedOrAudioMessage: Boolean(pinnedIds && pinnedIds.length) || Boolean(audioChatId && audioMessageId),\n customBackground,\n patternColor,\n isCustomBackgroundColor,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_MOBILE_SCREEN && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser',\n ]),\n)(MiddleColumn));\n","import { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { useEffect, useState } from '../lib/teact/teact';\n\nexport default (settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, CUSTOM_BG_CACHE_NAME, cacheApi.Type.Blob)\n .then((blob) => {\n setValue(`url(${URL.createObjectURL(blob)}`);\n });\n }\n }, [settingValue]);\n\n return value;\n};\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n} from '../../modules/selectors';\nimport { isChatAdmin, isChatChannel, isChatPrivate } from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport CalendarModal from '../common/CalendarModal.async';\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\n\ntype OwnProps = {\n chatId?: number;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canManage?: boolean;\n isChannel?: boolean;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupMembers,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nconst RightHeader: FC = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n profileState,\n managementScreen,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n searchMessagesByDate,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeCalendar();\n }, [closeCalendar, searchMessagesByDate]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n \n \n \n \n );\n case HeaderContent.ManageInitial:\n return

{lang('Edit')}

;\n case HeaderContent.ManageChatPrivacyType:\n return

{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}

;\n case HeaderContent.ManageDiscussion:\n return

{lang('Discussion')}

;\n case HeaderContent.ManageChatAdministrators:\n return

{lang('ChannelAdministrators')}

;\n case HeaderContent.ManageGroupRecentActions:\n return

{lang('Group.Info.AdminLog')}

;\n case HeaderContent.ManageGroupAdminRights:\n return

{lang('EditAdminRights')}

;\n case HeaderContent.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

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

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

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

{lang('GroupMembers')}

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

Profile

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

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {isVerifiedIconShown && }\n
\n )}\n {!isSavedMessages && renderStatus()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const {\n animationLevel,\n } = global.settings.byKey;\n\n return {\n lastSyncTime, user, chat, isSavedMessages, animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import {\n ApiChat, ApiMediaFormat, ApiPhoto, ApiUser,\n} from '../../../api/types';\nimport { useEffect } from '../../../lib/teact/teact';\nimport * as mediaLoader from '../../../util/mediaLoader';\n\nconst PHOTOS_TO_PRELOAD = 4;\n\nexport default function usePhotosPreload(\n profile: ApiUser | ApiChat | undefined,\n photos: ApiPhoto[],\n currentIndex: number,\n) {\n useEffect(() => {\n photos.slice(currentIndex, currentIndex + PHOTOS_TO_PRELOAD).forEach((photo) => {\n const mediaData = mediaLoader.getFromMemory(`photo${photo.id}?size=c`);\n if (!mediaData) {\n mediaLoader.fetch(`photo${photo.id}?size=c`, ApiMediaFormat.BlobUrl);\n }\n });\n }, [currentIndex, photos]);\n}\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { copyTextToClipboard } from '../../util/clipboard';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\nimport ListItem from '../ui/ListItem';\nimport Switcher from '../ui/Switcher';\n\ntype OwnProps = {\n chatOrUserId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n canInviteUsers?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst ChatExtra: FC = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n loadFullUser,\n showNotification,\n updateChatMutedState,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n const {\n id: chatId,\n isMuted: currentIsMuted,\n username: chatUsername,\n } = chat || {};\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const handleClick = useCallback((text: string, entity: string) => {\n copyTextToClipboard(text);\n showNotification({ message: `${entity} was copied` });\n }, [showNotification]);\n\n const handleNotificationChange = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !currentIsMuted });\n }, [chatId, currentIsMuted, updateChatMutedState]);\n\n if (!chat || chat.isRestricted || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n const bio = fullInfo && fullInfo.bio;\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n const description = getChatDescription(chat);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n const printedUsername = username || chatUsername;\n const printedDescription = bio || description;\n\n return (\n
\n {formattedNumber && !!formattedNumber.length && (\n handleClick(formattedNumber, lang('Phone'))}>\n {formattedNumber}\n {lang('Phone')}\n \n )}\n {printedUsername && (\n handleClick(`@${printedUsername}`, lang('Username'))}\n >\n {renderText(printedUsername)}\n {lang('Username')}\n \n )}\n {printedDescription && !!printedDescription.length && (\n handleClick(printedDescription, lang(userId ? 'UserBio' : 'Info'))}\n >\n {renderText(printedDescription, ['br', 'links', 'emoji'])}\n {lang(userId ? 'UserBio' : 'Info')}\n \n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n handleClick(link, lang('SetUrlPlaceholder'))}>\n
\n \n
\n {lang('SetUrlPlaceholder')}\n
\n )}\n \n {lang('Notifications')}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n const { lastSyncTime } = global;\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadFullUser', 'updateChatMutedState', 'showNotification',\n ]),\n)(ChatExtra));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType,\n} from '../../types';\n\nimport {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n isChatAdmin, isChatChannel, isChatGroup, isChatPrivate,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport ProfileInfo from './ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from './ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: number;\n userId?: number;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n members,\n usersById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n setLocalMediaSearchType,\n loadMoreMembers,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ]), [hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n usersById, chatMessages, foundIds, chatId, lastSyncTime,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'documents':\n text = 'No documents found.';\n break;\n case 'links':\n text = 'No links found.';\n break;\n case 'audio':\n text = 'No audio found.';\n break;\n default:\n text = 'No media found.';\n }\n\n return (\n
\n \n
\n );\n }\n\n return (\n
\n {resultType === 'media' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n
\n \n {renderSharedMedia}\n \n \n
\n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\n return (\n
\n \n \n
\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n\n let resolvedUserId;\n if (userId) {\n resolvedUserId = userId;\n } else if (isChatPrivate(chatId)) {\n resolvedUserId = chatId;\n }\n\n return {\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n ...(hasMembersTab && members && {\n members,\n usersById,\n }),\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat && chat.isRestricted,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default RightSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default ManagementAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default StickerSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default GifSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default PollResultsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState, RightColumnContent } from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: number;\n threadId?: number;\n currentProfileUserId?: number;\n isChatSelected: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\n ]),\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? : undefined;\n};\n\nexport default NotificationsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ErrorsAsync: FC = ({ isOpen }) => {\n const Errors = useModuleLoader(Bundles.Extra, 'Errors', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Errors ? : undefined;\n};\n\nexport default ErrorsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? : undefined;\n};\n\nexport default ForwardPickerAsync;\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n ANIMATION_END_DELAY, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport Notifications from './Notifications.async';\nimport Errors from './Errors.async';\nimport ForwardPicker from './ForwardPicker.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n animationLevel: number;\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasErrors: boolean;\n audioMessage?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet rightColumnAnimationTimeout: number | undefined;\nlet notificationInterval: number | undefined;\n\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n loadAnimatedEmojis,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n loadAnimatedEmojis();\n }\n }, [lastSyncTime, loadAnimatedEmojis]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n // For animating components in portals (i.e. Notification)\n document.body.classList.toggle('is-right-column-shown', className.includes('right-column-open'));\n }, [className]);\n\n // Add `body` classes when toggling right column\n useEffect(() => {\n if (animationLevel > 0) {\n document.body.classList.add('animating-right-column');\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n\n if (rightColumnAnimationTimeout) {\n clearTimeout(rightColumnAnimationTimeout);\n rightColumnAnimationTimeout = undefined;\n }\n\n rightColumnAnimationTimeout = window.setTimeout(() => {\n document.body.classList.remove('animating-right-column');\n rightColumnAnimationTimeout = undefined;\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isRightColumnShown]);\n\n useBackgroundMode(() => {\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n document.title = `${newUnread} notification${newUnread > 1 ? 's' : ''}`;\n updateIcon(true);\n }\n } else {\n document.title = PAGE_TITLE;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n document.title = PAGE_TITLE;\n }\n\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasErrors: Boolean(global.errors.length),\n audioMessage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis']),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/4.dbb569ca042ea30048a3.css b/dist/4.3009ada641e67eb52367.css similarity index 100% rename from dist/4.dbb569ca042ea30048a3.css rename to dist/4.3009ada641e67eb52367.css diff --git a/dist/4.dbb569ca042ea30048a3.js b/dist/4.3009ada641e67eb52367.js similarity index 98% rename from dist/4.dbb569ca042ea30048a3.js rename to dist/4.3009ada641e67eb52367.js index a52ddf5e..5aa0fa23 100644 --- a/dist/4.dbb569ca042ea30048a3.js +++ b/dist/4.3009ada641e67eb52367.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{103:function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},106:function(e,t,n){"use strict";var r=n(0),a=n(7),o=n(9),c=n(8),i=n(43),l=n(127);let u,s;async function d(){return u||(u=n.e(6).then(n.bind(null,181)),s=(await u).default),u}setTimeout(d,5e3);t.a=Object(r.h)(({className:e,id:t,animationData:n,play:u,playSegment:f,speed:m,noLoop:h,size:b,quality:p,isLowPriority:v,onLoad:g})=>{const[E,j]=Object(r.r)(),O=Object(r.q)(null),y=Object(r.q)(!1),w=Object(r.q)(!1),k=Object(r.q)();k.current=u;const N=Object(r.q)();N.current=f,Object(r.n)(()=>{if(E||!n)return;const e=()=>{if(!O.current)return;const e=new s(t,O.current,n,{noLoop:h,size:b,quality:p,isLowPriority:v},g);m&&e.setSpeed(m),j(e)};s?e():d().then(()=>{Object(o.b)(()=>{O.current&&e()})})},[E,n,t,v,h,g,p,b,m]),Object(r.n)(()=>()=>{E&&E.destroy()},[E]);const C=Object(r.m)((e=!1)=>{E&&(k.current||N.current)&&(N.current?E.playSegment(N.current):e?E.goToAndPlay(0):E.play())},[E]),L=Object(r.m)(()=>{E&&E.pause()},[E]),A=Object(r.m)(()=>{w.current=!0,E&&(y.current||(y.current=E.isPlaying()),L())},[E,L]),M=Object(r.m)(()=>{y.current&&C(),y.current=!1,w.current=!1},[C]),P=Object(r.m)(()=>{Object(o.b)(M)},[M]);Object(r.n)(()=>{E&&(u||f?w.current?y.current=!0:C(h):w.current?y.current=!1:L())},[E,u,f,h,C,L]),Object(i.a)(A,M),Object(l.a)(A,P);const T=Object(c.a)("AnimatedSticker",e,a.d&&u&&"is-playing"),S=b?`width: ${b}px; height: ${b}px;`:void 0;return r.a.createElement("div",{ref:O,className:T,style:S})})},113:function(e,t,n){"use strict";var r=n(0),a=n(57);t.a=({containerId:e,className:t,children:n})=>{const o=Object(r.q)(document.createElement("div"));return Object(r.o)(()=>{const n=document.querySelector(e||"#portals");if(!n)return;const r=o.current;return t&&r.classList.add(t),n.appendChild(r),()=>{a.a.render(void 0,r),n.removeChild(r)}},[t,e]),a.a.render(n,o.current)}},116:function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(4),a=n(48);const o={MonkeyIdle:n.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:n.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:n.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:n.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:n.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:n.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:n.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function c(e){const t=o[e].replace(window.location.origin,"");return a.b("file"+t,r.ApiMediaFormat.Lottie)}},120:function(e,t,n){"use strict";var r=n(0),a=n(8),o=n(1),c=n(14),i=n(94),l=n(25),u=n(99),s=n(16);n(141);const d={type:"blob",quality:.8,format:"jpeg",circle:!1};let f,m,h;var b=Object(r.h)(({file:e,onChange:t,onClose:a})=>{const[b,p]=Object(r.r)(!1);Object(r.n)(()=>{e&&(b?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:n,offsetHeight:r}=t;h=new f(t,{enableZoom:!0,boundary:{width:n,height:r},viewport:{width:n-16,height:r-16,type:"circle"}});const a=await Object(c.a)(e);await h.bind({url:a})}catch(e){o.o&&console.error(e)}}(e):async function(){return m||(m=Promise.all([n.e(5),n.e(7)]).then(n.bind(null,304)),f=(await m).default),m}().then(()=>p(!0)))},[e,b]);const v=Object(i.a)();return r.a.createElement(u.a,{isOpen:Boolean(e),onClose:a,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},b?r.a.createElement("div",{id:"avatar-crop"}):r.a.createElement(s.a,null),r.a.createElement(l.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!h)return;const e=await h.result(d),n="string"==typeof e?e:Object(c.b)(e,"avatar.jpg");t(n)},ariaLabel:v("CropImage")},r.a.createElement("i",{className:"icon-check"})))});n(142);t.a=Object(r.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:n,onChange:o})=>{const[c,i]=Object(r.r)(),[l,u]=Object(r.r)(n);Object(r.n)(()=>{u(n)},[n]);const s=Object(a.a)(l&&"filled",t&&"disabled");return r.a.createElement("div",{className:"AvatarEditable"},r.a.createElement("label",{className:s,role:"button",tabIndex:0,title:e},r.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(i(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),r.a.createElement("i",{className:"icon-camera-add"}),l&&r.a.createElement("img",{src:l,alt:"Avatar"})),r.a.createElement(b,{file:c,onClose:function(){i(void 0)},onChange:function(e){i(void 0),o(e),l&&URL.revokeObjectURL(l),u(URL.createObjectURL(e))}}))})},127:function(e,t,n){"use strict";var r=n(0);t.a=(e,t)=>{Object(r.n)(()=>(document.hasFocus()||e(),window.addEventListener("blur",e),window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t),window.removeEventListener("blur",e)}),[e,t])}},128:function(e,t,n){},138:function(e,t,n){"use strict";var r=n(0),a=n(1),o=n(7),c=n(116),i=n(106);n(128);const l=[0,50],u=[0,20],s=[20,0],d=o.f?a.pb:a.ob;t.a=Object(r.h)(({isPasswordVisible:e,isBig:t})=>{const[n,o]=Object(r.r)(),[f,m]=Object(r.r)(),[h,b]=Object(r.r)(!1),[p,v]=Object(r.r)(!1);Object(r.n)(()=>{n?setTimeout(()=>v(!0),2e3):Object(c.a)("MonkeyClose").then(o)},[n]),Object(r.n)(()=>{f||Object(c.a)("MonkeyPeek").then(m)},[f]);const g=Object(r.m)(()=>b(!0),[]);return r.a.createElement("div",{id:"monkey",className:t?"big":""},!h&&r.a.createElement("div",{className:"monkey-preview"}),n&&r.a.createElement(i.a,{id:"closeMonkey",size:t?a.zb:d,className:p?"hidden":"shown",animationData:n,playSegment:l,noLoop:!0,onLoad:g}),f&&r.a.createElement(i.a,{id:"peekMonkey",size:t?a.zb:d,className:p?"shown":"hidden",animationData:f,playSegment:e?u:s,noLoop:!0}))})},139:function(e,t,n){"use strict";var r=n(0),a=n(1),o=n(7),c=n(8),i=n(25);const l=o.f?550:400;t.a=Object(r.h)(({isLoading:e=!1,isPasswordVisible:t,error:n,hint:u,placeholder:s="Password",submitLabel:d="Next",clearError:f,onChangePasswordVisibility:m,onInputChange:h,onSubmit:b})=>{const p=Object(r.q)(null),[v,g]=Object(r.r)(""),[E,j]=Object(r.r)(!1);return Object(r.n)(()=>{o.k||setTimeout(()=>{p.current.focus()},l)},[]),Object(r.n)(()=>{n&&requestAnimationFrame(()=>{p.current.focus(),p.current.select()})},[n]),r.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||E&&b(v)},autoComplete:"off"},r.a.createElement("div",{className:Object(c.a)("input-group password-input",v&&"touched",n&&"error")},r.a.createElement("input",{ref:p,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:v||"",autoComplete:"current-password",onChange:function(e){n&&f();const{target:t}=e;g(t.value),j(t.value.length>=a.X),h&&h(t.value)}}),r.a.createElement("label",null,n||u||s),r.a.createElement("div",{className:"toggle-password",onClick:function(){m(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},r.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),E&&r.a.createElement(i.a,{type:"submit",ripple:!0,isLoading:e},d))})},140:function(e,t,n){},141:function(e,t,n){},142:function(e,t,n){},93:function(e,t,n){"use strict";n.r(t),n.d(t,"AuthCode",(function(){return b})),n.d(t,"AuthPassword",(function(){return g})),n.d(t,"AuthRegister",(function(){return O})),n.d(t,"AuthQrCode",(function(){return C}));var r=n(0),a=n(2),o=n(7),c=n(3),i=n(40),l=n(16),u=n(1),s=n(116),d=n(106);n(128);const f=o.f?u.pb:u.ob;var m=Object(r.h)(({code:e,codeLength:t,trackingDirection:n,isTracking:a,isBig:o})=>{const[c,i]=Object(r.r)(),[l,m]=Object(r.r)(),[h,b]=Object(r.r)(!1),p=165/t;Object(r.n)(()=>{c||Object(s.a)("MonkeyIdle").then(i)},[c]),Object(r.n)(()=>{l||Object(s.a)("MonkeyTracking").then(m)},[l]);const v=Object(r.m)(()=>b(!0),[]);return r.a.createElement("div",{id:"monkey",className:o?"big":""},!h&&r.a.createElement("div",{className:"monkey-preview"}),c&&r.a.createElement(d.a,{id:"idleMonkey",size:o?u.zb:f,className:a?"hidden":void 0,animationData:c,play:!a,onLoad:v}),l&&r.a.createElement(d.a,{id:"trackingMonkey",size:o?u.zb:f,className:a?"shown":"hidden",animationData:l,playSegment:a?function(){const r=e&&e.length>1||n<0?15+p*(e.length-1):0,a=e.length===t?180:15+p*e.length;return n<1?[a,r]:[r,a]}():void 0,speed:2,noLoop:!0}))});function h(e){function t(){e()}return window.addEventListener("popstate",t),window.history.pushState({},""),()=>{window.removeEventListener("popstate",t),window.history.back()}}var b=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authPhoneNumber","authIsCodeViaApp","authIsLoading","authError"]),(e,t)=>Object(c.l)(t,["setAuthCode","returnToAuthPhoneNumber","clearAuthError"]))(({authPhoneNumber:e,authIsCodeViaApp:t,authIsLoading:n,authError:a,setAuthCode:c,returnToAuthPhoneNumber:u,clearAuthError:s})=>{const d=Object(r.q)(null),[f,b]=Object(r.r)(""),[p,v]=Object(r.r)(!1),[g,E]=Object(r.r)(1);Object(r.n)(()=>{o.k||d.current.focus()},[]),h(u);const j=Object(r.m)(e=>{a&&s();const{currentTarget:t}=e;t.value=t.value.replace(/[^\d]+/,"").substr(0,5),t.value!==f&&(b(t.value),p?t.value.length||v(!1):v(!0),f&&f.length>t.value.length?E(-1):E(1),5===t.value.length&&c({code:t.value}))},[a,s,f,p,c]);return r.a.createElement("div",{id:"auth-code-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement(m,{code:f,codeLength:5,isTracking:p,trackingDirection:g}),r.a.createElement("h2",null,e,r.a.createElement("div",{className:"auth-number-edit",onClick:u,role:"button",tabIndex:0,title:"Sign In with another phone number"},r.a.createElement("i",{className:"icon-edit"}))),r.a.createElement("p",{className:"note"},t?r.a.createElement(r.a.Fragment,null,"We have sent the code to the Telegram app",r.a.createElement("br",null),"on your other device."):r.a.createElement(r.a.Fragment,null,"We have sent you an SMS",r.a.createElement("br",null),"with the code.")),r.a.createElement(i.a,{ref:d,id:"sign-in-code",label:"Code",onInput:j,value:f,error:a,autoComplete:"one-time-code",inputMode:"decimal"}),n&&r.a.createElement(l.a,null)))})),p=n(138),v=n(139);var g=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authIsLoading","authError","authHint"]),(e,t)=>Object(c.l)(t,["setAuthPassword","clearAuthError"]))(({authIsLoading:e,authError:t,authHint:n,setAuthPassword:a,clearAuthError:o})=>{const[c,i]=Object(r.r)(!1),l=Object(r.m)(e=>{i(e)},[]),u=Object(r.m)(e=>{a({password:e})},[a]);return r.a.createElement("div",{id:"auth-password-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement(p.a,{isPasswordVisible:c}),r.a.createElement("h2",null,"Enter Your Password"),r.a.createElement("p",{className:"note"},"Your account is protected with",r.a.createElement("br",null),"an additional password."),r.a.createElement(v.a,{clearError:o,error:t,hint:n,isLoading:e,isPasswordVisible:c,onChangePasswordVisibility:l,onSubmit:u})))})),E=n(25),j=n(120);var O=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authIsLoading","authError"]),(e,t)=>Object(c.l)(t,["signUp","clearAuthError","uploadProfilePhoto"]))(({authIsLoading:e,authError:t,signUp:n,clearAuthError:a,uploadProfilePhoto:o})=>{const[c,l]=Object(r.r)(!1),[u,s]=Object(r.r)(),[d,f]=Object(r.r)(""),[m,h]=Object(r.r)("");return r.a.createElement("div",{id:"auth-registration-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement("form",{action:"",method:"post",onSubmit:function(e){e.preventDefault(),n({firstName:d,lastName:m}),u&&o({file:u})}},r.a.createElement(j.a,{onChange:s}),r.a.createElement("h2",null,"Your Name"),r.a.createElement("p",{className:"note"},"Enter your name and add",r.a.createElement("br",null),"a profile picture."),r.a.createElement(i.a,{id:"registration-first-name",label:"Name",onChange:function(e){t&&a();const{target:n}=e;f(n.value),l(n.value.length>0)},value:d,error:t,autoComplete:"given-name"}),r.a.createElement(i.a,{id:"registration-last-name",label:"Last Name (optional)",onChange:function(e){const{target:t}=e;h(t.value)},value:m,autoComplete:"family-name"}),c&&r.a.createElement(E.a,{type:"submit",ripple:!0,isLoading:e},"Start Messaging"))))}));let y=null;class w{}w.render=function(e,t){y(e,t)},self.QrCreator=w,function(e){function t(t,n,r,a){var o={},c=e(r,n);c.u(t),c.J(),a=a||0;var i=c.h(),l=c.h()+2*a;return o.text=t,o.level=n,o.version=r,o.O=l,o.a=function(e,t){return t-=a,!(0>(e-=a)||e>=i||0>t||t>=i)&&c.a(e,t)},o}function n(e,t,n,r,a,o,c,i,l,u){function s(t,n,r,a,c,i,l){t?(e.lineTo(n+i,r+l),e.arcTo(n,r,a,c,o)):e.lineTo(n,r)}c?e.moveTo(t+o,n):e.moveTo(t,n),s(i,r,n,r,a,-o,0),s(l,r,a,t,a,0,-o),s(u,t,a,t,n,o,0),s(c,t,n,r,n,0,o)}function r(e,t,n,r,a,o,c,i,l,u){function s(t,n,r,a){e.moveTo(t+r,n),e.lineTo(t,n),e.lineTo(t,n+a),e.arcTo(t,n,t+r,n,o)}c&&s(t,n,o,o),i&&s(r,n,-o,o),l&&s(r,a,-o,-o),u&&s(t,a,o,-o)}function a(e,a){e:{var o=a.text,c=a.v,i=a.N,l=a.K,u=a.P;for(i=Math.max(1,i||1),l=Math.min(40,l||40);i<=l;i+=1)try{var s=t(o,c,i,u);break e}catch(e){}s=void 0}if(!s)return null;for(o=e.getContext("2d"),a.background&&(o.fillStyle=a.background,o.fillRect(a.left,a.top,a.size,a.size)),c=s.O,l=a.size/c,o.beginPath(),u=0;uMath.round(e*t.size)),"linear-gradient"===r)var o=e.createLinearGradient.apply(e,n);else{if("radial-gradient"!==r)throw Error("Unsupported fill");o=e.createRadialGradient.apply(e,n)}a.forEach(([e,t])=>{o.addColorStop(e,t)}),e.fillStyle=o}}(o,a),o.fill(),e}var o={minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:.5,quiet:0};y=function(e,t){var n={};Object.assign(n,o,e),n.N=n.minVersion,n.K=n.maxVersion,n.v=n.ecLevel,n.left=n.left,n.top=n.top,n.size=n.size,n.fill=n.fill,n.background=n.background,n.text=n.text,n.R=n.radius,n.P=n.quiet,t instanceof HTMLCanvasElement?(t.width===n.size&&t.height===n.size||(t.width=n.size,t.height=n.size),t.getContext("2d").clearRect(0,0,t.width,t.height),a(t,n)):((e=document.createElement("canvas")).width=n.size,e.height=n.size,n=a(e,n),t.appendChild(n))}}(function(){function e(a,c){function i(e,t){for(var n=-1;7>=n;n+=1)if(!(-1>=e+n||d<=e+n))for(var r=-1;7>=r;r+=1)-1>=t+r||d<=t+r||(s[e+n][t+r]=0<=n&&6>=n&&(0==r||6==r)||0<=r&&6>=r&&(0==n||6==n)||2<=n&&4>=n&&2<=r&&4>=r)}function l(e,n){for(var c=d=4*a+17,l=Array(c),h=0;h=v;v+=1)for(var g=-2;2>=g;g+=1)s[b+v][p+g]=-2==v||2==v||-2==g||2==g||0==v&&0==g}for(c=8;cl;l+=1)h=!e&&1==(c>>l&1),s[6>l?l:8>l?l+1:d-15+l][8]=h,s[8][8>l?d-l-1:9>l?15-l:14-l]=h;if(s[d-8][8]=!e,7<=a){for(c=r.A(a),l=0;18>l;l+=1)h=!e&&1==(c>>l&1),s[Math.floor(l/3)][l%3+d-8-3]=h;for(l=0;18>l;l+=1)h=!e&&1==(c>>l&1),s[l%3+d-8-3][Math.floor(l/3)]=h}if(null==f){for(e=o.I(a,u),c=function(){var e=[],t=0,n={B:function(){return e},c:function(t){return 1==(e[Math.floor(t/8)]>>>7-t%8&1)},put:function(e,t){for(var r=0;r>>t-r-1&1))},f:function(){return t},m:function(n){var r=Math.floor(t/8);e.length<=r&&e.push(0),n&&(e[r]|=128>>>t%8),t+=1}};return n}(),l=0;l8*h)throw Error("code length overflow. ("+c.f()+">"+8*h+")");for(c.f()+4<=8*h&&c.put(0,4);0!=c.f()%8;)c.m(!1);for(;!(c.f()>=8*h)&&(c.put(236,8),!(c.f()>=8*h));)c.put(17,8);var E=0;for(h=l=0,b=Array(e.length),p=Array(e.length),v=0;vv;v+=1)null==s[l][p-v]&&(g=!1,b>>h&1)),n(l,p-v)&&(g=!g),s[l][p-v]=g,-1==--h&&(b+=1,h=7));if(0>(l+=c)||d<=l){l-=c,c=-c;break}}}var u=n[c],s=null,d=0,f=null,m=[],h={u:function(t){t=function(t){var n=e.s(t);return{S:function(){return 4},b:function(){return n.length},write:function(e){for(var t=0;te||d<=e||0>t||d<=t)throw Error(e+","+t);return s[e][t]},h:function(){return d},J:function(){for(var e=0,t=0,n=0;8>n;n+=1){l(!0,n);var a=r.D(h);(0==n||e>a)&&(e=a,t=n)}l(!1,t)}};return h}function t(e,n){if(void 0===e.length)throw Error(e.length+"/"+n);var r=function(){for(var t=0;to.b()-e.b())return o;for(var n=a.g(o.c(0))-a.g(e.c(0)),r=Array(o.b()),c=0;cr?t.push(r):2048>r?t.push(192|r>>6,128|63&r):55296>r||57344<=r?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return t};var n={L:1,M:0,Q:3,H:2},r=function(){function e(e){for(var t=0;0!=e;)t+=1,e>>>=1;return t}var n=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]];return{w:function(t){for(var n=t<<10;0<=e(n)-e(1335);)n^=1335<t||40t?8:16},D:function(e){for(var t=e.h(),n=0,r=0;r=i;i+=1)if(!(0>r+i||t<=r+i))for(var l=-1;1>=l;l+=1)0>a+l||t<=a+l||(0!=i||0!=l)&&c==e.a(r+i,a+l)&&(o+=1);5n;n+=1)e[n]=1<n;n+=1)e[n]=e[n-4]^e[n-5]^e[n-6]^e[n-8];for(n=0;255>n;n+=1)t[e[n]]=n;return{g:function(e){if(1>e)throw Error("glog("+e+")");return t[e]},i:function(t){for(;0>t;)t+=255;for(;256<=t;)t-=255;return e[t]}}}(),o=function(){function e(e,r){switch(r){case n.L:return t[4*(e-1)];case n.M:return t[4*(e-1)+1];case n.Q:return t[4*(e-1)+2];case n.H:return t[4*(e-1)+3]}}var t=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];return{I:function(t,n){var r=e(t,n);if(void 0===r)throw Error("bad rs block @ typeNumber:"+t+"/errorCorrectLevel:"+n);t=r.length/3,n=[];for(var a=0;aObject(c.l)(e,["connectionState","authQrCode"]),(e,t)=>Object(c.l)(t,["returnToAuthPhoneNumber"]))(({connectionState:e,authQrCode:t,returnToAuthPhoneNumber:n})=>{const a=Object(r.q)(null);return Object(r.n)(()=>{if(!t||"connectionStateReady"!==e)return;const n=a.current;n.innerHTML="",n.classList.remove("pre-animate"),k.render({text:"tg://login?token="+t.token,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},n)},[e,t]),h(n),r.a.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement("div",{className:Object(N.a)("qr-container",t&&"pre-animate"),ref:a},!t&&r.a.createElement(l.a,null)),r.a.createElement("h3",null," Log in to Telegram by QR Code"),r.a.createElement("ol",null,r.a.createElement("li",null,r.a.createElement("span",null,"Open Telegram on your phone")),r.a.createElement("li",null,r.a.createElement("span",null,"Go to ",r.a.createElement("b",null,"Settings")," > ",r.a.createElement("b",null,"Devices")," > ",r.a.createElement("b",null,"Scan QR"))),r.a.createElement("li",null,r.a.createElement("span",null,"Point your phone at this screen to confirm login"))),r.a.createElement(E.a,{isText:!0,onClick:n},"Log in by phone number")))}))},94:function(e,t,n){"use strict";var r=n(11),a=n(31),o=n(103);t.a=()=>{const e=Object(a.a)();return Object(o.a)(()=>r.a(e),[e]),r.b}},99:function(e,t,n){"use strict";var r=n(0),a=n(50);var o=n(8),c=n(43),i=n(29),l=n(52),u=n(94),s=n(25),d=n(113);n(140);t.a=e=>{const{title:t,className:n,isOpen:f,header:m,hasCloseButton:h,noBackdrop:b,children:p,onClose:v,onCloseAnimationEnd:g,onEnter:E}=e,{shouldRender:j,transitionClassNames:O}=Object(i.a)(f,g),y=Object(r.q)(null);Object(r.n)(()=>f?Object(a.a)({onEsc:v,onEnter:E}):void 0,[f,v,E]),Object(r.n)(()=>f&&y.current?function(e){function t(t){if("Tab"!==t.key)return;t.preventDefault(),t.stopPropagation();const n=Array.from(e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(!n.length)return;const r=n.findIndex(e=>e.isSameNode(document.activeElement));let a=0;r>=0&&(a=t.shiftKey?r>0?r-1:n.length-1:r{document.removeEventListener("keydown",t,!1)}}(y.current):void 0,[f]),Object(l.a)(([e])=>(document.body.classList.toggle("has-open-dialog",f),(f||!f&&void 0!==e)&&Object(c.b)(200),()=>{document.body.classList.remove("has-open-dialog")}),[f]);const w=Object(u.a)();if(!j)return;const k=Object(o.a)("Modal",n,O,b&&"transparent-backdrop");return r.a.createElement(d.a,null,r.a.createElement("div",{ref:y,className:k,tabIndex:-1,role:"dialog"},r.a.createElement("div",{className:"modal-container"},r.a.createElement("div",{className:"modal-backdrop",onClick:v}),r.a.createElement("div",{className:"modal-dialog"},m||(t?r.a.createElement("div",{className:"modal-header"},h&&r.a.createElement(s.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:w("Close"),onClick:v},r.a.createElement("i",{className:"icon-close"})),r.a.createElement("div",{className:"modal-title"},t)):void 0),r.a.createElement("div",{className:"modal-content custom-scroll"},p)))))}}}]); -//# sourceMappingURL=4.dbb569ca042ea30048a3.js.map \ No newline at end of file +(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{103:function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},106:function(e,t,n){"use strict";var r=n(0),a=n(7),o=n(9),c=n(8),i=n(43),l=n(121);let u,s;async function d(){return u||(u=n.e(6).then(n.bind(null,181)),s=(await u).default),u}setTimeout(d,5e3);t.a=Object(r.h)(({className:e,id:t,animationData:n,play:u,playSegment:f,speed:m,noLoop:h,size:b,quality:p,isLowPriority:v,onLoad:g})=>{const[E,j]=Object(r.r)(),O=Object(r.q)(null),y=Object(r.q)(!1),w=Object(r.q)(!1),k=Object(r.q)();k.current=u;const N=Object(r.q)();N.current=f,Object(r.n)(()=>{if(E||!n)return;const e=()=>{if(!O.current)return;const e=new s(t,O.current,n,{noLoop:h,size:b,quality:p,isLowPriority:v},g);m&&e.setSpeed(m),j(e)};s?e():d().then(()=>{Object(o.b)(()=>{O.current&&e()})})},[E,n,t,v,h,g,p,b,m]),Object(r.n)(()=>()=>{E&&E.destroy()},[E]);const C=Object(r.m)((e=!1)=>{E&&(k.current||N.current)&&(N.current?E.playSegment(N.current):e?E.goToAndPlay(0):E.play())},[E]),L=Object(r.m)(()=>{E&&E.pause()},[E]),A=Object(r.m)(()=>{w.current=!0,E&&(y.current||(y.current=E.isPlaying()),L())},[E,L]),M=Object(r.m)(()=>{y.current&&C(),y.current=!1,w.current=!1},[C]),P=Object(r.m)(()=>{Object(o.b)(M)},[M]);Object(r.n)(()=>{E&&(u||f?w.current?y.current=!0:C(h):w.current?y.current=!1:L())},[E,u,f,h,C,L]),Object(i.a)(A,M),Object(l.a)(A,P);const T=Object(c.a)("AnimatedSticker",e,a.d&&u&&"is-playing"),S=b?`width: ${b}px; height: ${b}px;`:void 0;return r.a.createElement("div",{ref:O,className:T,style:S})})},113:function(e,t,n){"use strict";var r=n(0),a=n(57);t.a=({containerId:e,className:t,children:n})=>{const o=Object(r.q)(document.createElement("div"));return Object(r.o)(()=>{const n=document.querySelector(e||"#portals");if(!n)return;const r=o.current;return t&&r.classList.add(t),n.appendChild(r),()=>{a.a.render(void 0,r),n.removeChild(r)}},[t,e]),a.a.render(n,o.current)}},116:function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(4),a=n(48);const o={MonkeyIdle:n.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:n.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:n.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:n.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:n.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:n.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:n.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function c(e){const t=o[e].replace(window.location.origin,"");return a.b("file"+t,r.ApiMediaFormat.Lottie)}},120:function(e,t,n){"use strict";var r=n(0),a=n(8),o=n(1),c=n(14),i=n(94),l=n(25),u=n(99),s=n(16);n(141);const d={type:"blob",quality:.8,format:"jpeg",circle:!1};let f,m,h;var b=Object(r.h)(({file:e,onChange:t,onClose:a})=>{const[b,p]=Object(r.r)(!1);Object(r.n)(()=>{e&&(b?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:n,offsetHeight:r}=t;h=new f(t,{enableZoom:!0,boundary:{width:n,height:r},viewport:{width:n-16,height:r-16,type:"circle"}});const a=await Object(c.a)(e);await h.bind({url:a})}catch(e){o.o&&console.error(e)}}(e):async function(){return m||(m=Promise.all([n.e(5),n.e(7)]).then(n.bind(null,304)),f=(await m).default),m}().then(()=>p(!0)))},[e,b]);const v=Object(i.a)();return r.a.createElement(u.a,{isOpen:Boolean(e),onClose:a,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},b?r.a.createElement("div",{id:"avatar-crop"}):r.a.createElement(s.a,null),r.a.createElement(l.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!h)return;const e=await h.result(d),n="string"==typeof e?e:Object(c.b)(e,"avatar.jpg");t(n)},ariaLabel:v("CropImage")},r.a.createElement("i",{className:"icon-check"})))});n(142);t.a=Object(r.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:n,onChange:o})=>{const[c,i]=Object(r.r)(),[l,u]=Object(r.r)(n);Object(r.n)(()=>{u(n)},[n]);const s=Object(a.a)(l&&"filled",t&&"disabled");return r.a.createElement("div",{className:"AvatarEditable"},r.a.createElement("label",{className:s,role:"button",tabIndex:0,title:e},r.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(i(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),r.a.createElement("i",{className:"icon-camera-add"}),l&&r.a.createElement("img",{src:l,alt:"Avatar"})),r.a.createElement(b,{file:c,onClose:function(){i(void 0)},onChange:function(e){i(void 0),o(e),l&&URL.revokeObjectURL(l),u(URL.createObjectURL(e))}}))})},121:function(e,t,n){"use strict";var r=n(0);t.a=(e,t)=>{Object(r.n)(()=>(document.hasFocus()||e(),window.addEventListener("blur",e),window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t),window.removeEventListener("blur",e)}),[e,t])}},129:function(e,t,n){},138:function(e,t,n){"use strict";var r=n(0),a=n(1),o=n(7),c=n(116),i=n(106);n(129);const l=[0,50],u=[0,20],s=[20,0],d=o.f?a.pb:a.ob;t.a=Object(r.h)(({isPasswordVisible:e,isBig:t})=>{const[n,o]=Object(r.r)(),[f,m]=Object(r.r)(),[h,b]=Object(r.r)(!1),[p,v]=Object(r.r)(!1);Object(r.n)(()=>{n?setTimeout(()=>v(!0),2e3):Object(c.a)("MonkeyClose").then(o)},[n]),Object(r.n)(()=>{f||Object(c.a)("MonkeyPeek").then(m)},[f]);const g=Object(r.m)(()=>b(!0),[]);return r.a.createElement("div",{id:"monkey",className:t?"big":""},!h&&r.a.createElement("div",{className:"monkey-preview"}),n&&r.a.createElement(i.a,{id:"closeMonkey",size:t?a.zb:d,className:p?"hidden":"shown",animationData:n,playSegment:l,noLoop:!0,onLoad:g}),f&&r.a.createElement(i.a,{id:"peekMonkey",size:t?a.zb:d,className:p?"shown":"hidden",animationData:f,playSegment:e?u:s,noLoop:!0}))})},139:function(e,t,n){"use strict";var r=n(0),a=n(1),o=n(7),c=n(8),i=n(25);const l=o.f?550:400;t.a=Object(r.h)(({isLoading:e=!1,isPasswordVisible:t,error:n,hint:u,placeholder:s="Password",submitLabel:d="Next",clearError:f,onChangePasswordVisibility:m,onInputChange:h,onSubmit:b})=>{const p=Object(r.q)(null),[v,g]=Object(r.r)(""),[E,j]=Object(r.r)(!1);return Object(r.n)(()=>{o.k||setTimeout(()=>{p.current.focus()},l)},[]),Object(r.n)(()=>{n&&requestAnimationFrame(()=>{p.current.focus(),p.current.select()})},[n]),r.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||E&&b(v)},autoComplete:"off"},r.a.createElement("div",{className:Object(c.a)("input-group password-input",v&&"touched",n&&"error")},r.a.createElement("input",{ref:p,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:v||"",autoComplete:"current-password",onChange:function(e){n&&f();const{target:t}=e;g(t.value),j(t.value.length>=a.X),h&&h(t.value)}}),r.a.createElement("label",null,n||u||s),r.a.createElement("div",{className:"toggle-password",onClick:function(){m(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},r.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),E&&r.a.createElement(i.a,{type:"submit",ripple:!0,isLoading:e},d))})},140:function(e,t,n){},141:function(e,t,n){},142:function(e,t,n){},93:function(e,t,n){"use strict";n.r(t),n.d(t,"AuthCode",(function(){return b})),n.d(t,"AuthPassword",(function(){return g})),n.d(t,"AuthRegister",(function(){return O})),n.d(t,"AuthQrCode",(function(){return C}));var r=n(0),a=n(2),o=n(7),c=n(3),i=n(40),l=n(16),u=n(1),s=n(116),d=n(106);n(129);const f=o.f?u.pb:u.ob;var m=Object(r.h)(({code:e,codeLength:t,trackingDirection:n,isTracking:a,isBig:o})=>{const[c,i]=Object(r.r)(),[l,m]=Object(r.r)(),[h,b]=Object(r.r)(!1),p=165/t;Object(r.n)(()=>{c||Object(s.a)("MonkeyIdle").then(i)},[c]),Object(r.n)(()=>{l||Object(s.a)("MonkeyTracking").then(m)},[l]);const v=Object(r.m)(()=>b(!0),[]);return r.a.createElement("div",{id:"monkey",className:o?"big":""},!h&&r.a.createElement("div",{className:"monkey-preview"}),c&&r.a.createElement(d.a,{id:"idleMonkey",size:o?u.zb:f,className:a?"hidden":void 0,animationData:c,play:!a,onLoad:v}),l&&r.a.createElement(d.a,{id:"trackingMonkey",size:o?u.zb:f,className:a?"shown":"hidden",animationData:l,playSegment:a?function(){const r=e&&e.length>1||n<0?15+p*(e.length-1):0,a=e.length===t?180:15+p*e.length;return n<1?[a,r]:[r,a]}():void 0,speed:2,noLoop:!0}))});function h(e){function t(){e()}return window.addEventListener("popstate",t),window.history.pushState({},""),()=>{window.removeEventListener("popstate",t),window.history.back()}}var b=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authPhoneNumber","authIsCodeViaApp","authIsLoading","authError"]),(e,t)=>Object(c.l)(t,["setAuthCode","returnToAuthPhoneNumber","clearAuthError"]))(({authPhoneNumber:e,authIsCodeViaApp:t,authIsLoading:n,authError:a,setAuthCode:c,returnToAuthPhoneNumber:u,clearAuthError:s})=>{const d=Object(r.q)(null),[f,b]=Object(r.r)(""),[p,v]=Object(r.r)(!1),[g,E]=Object(r.r)(1);Object(r.n)(()=>{o.k||d.current.focus()},[]),h(u);const j=Object(r.m)(e=>{a&&s();const{currentTarget:t}=e;t.value=t.value.replace(/[^\d]+/,"").substr(0,5),t.value!==f&&(b(t.value),p?t.value.length||v(!1):v(!0),f&&f.length>t.value.length?E(-1):E(1),5===t.value.length&&c({code:t.value}))},[a,s,f,p,c]);return r.a.createElement("div",{id:"auth-code-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement(m,{code:f,codeLength:5,isTracking:p,trackingDirection:g}),r.a.createElement("h2",null,e,r.a.createElement("div",{className:"auth-number-edit",onClick:u,role:"button",tabIndex:0,title:"Sign In with another phone number"},r.a.createElement("i",{className:"icon-edit"}))),r.a.createElement("p",{className:"note"},t?r.a.createElement(r.a.Fragment,null,"We have sent the code to the Telegram app",r.a.createElement("br",null),"on your other device."):r.a.createElement(r.a.Fragment,null,"We have sent you an SMS",r.a.createElement("br",null),"with the code.")),r.a.createElement(i.a,{ref:d,id:"sign-in-code",label:"Code",onInput:j,value:f,error:a,autoComplete:"one-time-code",inputMode:"decimal"}),n&&r.a.createElement(l.a,null)))})),p=n(138),v=n(139);var g=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authIsLoading","authError","authHint"]),(e,t)=>Object(c.l)(t,["setAuthPassword","clearAuthError"]))(({authIsLoading:e,authError:t,authHint:n,setAuthPassword:a,clearAuthError:o})=>{const[c,i]=Object(r.r)(!1),l=Object(r.m)(e=>{i(e)},[]),u=Object(r.m)(e=>{a({password:e})},[a]);return r.a.createElement("div",{id:"auth-password-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement(p.a,{isPasswordVisible:c}),r.a.createElement("h2",null,"Enter Your Password"),r.a.createElement("p",{className:"note"},"Your account is protected with",r.a.createElement("br",null),"an additional password."),r.a.createElement(v.a,{clearError:o,error:t,hint:n,isLoading:e,isPasswordVisible:c,onChangePasswordVisibility:l,onSubmit:u})))})),E=n(25),j=n(120);var O=Object(r.h)(Object(a.h)(e=>Object(c.l)(e,["authIsLoading","authError"]),(e,t)=>Object(c.l)(t,["signUp","clearAuthError","uploadProfilePhoto"]))(({authIsLoading:e,authError:t,signUp:n,clearAuthError:a,uploadProfilePhoto:o})=>{const[c,l]=Object(r.r)(!1),[u,s]=Object(r.r)(),[d,f]=Object(r.r)(""),[m,h]=Object(r.r)("");return r.a.createElement("div",{id:"auth-registration-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement("form",{action:"",method:"post",onSubmit:function(e){e.preventDefault(),n({firstName:d,lastName:m}),u&&o({file:u})}},r.a.createElement(j.a,{onChange:s}),r.a.createElement("h2",null,"Your Name"),r.a.createElement("p",{className:"note"},"Enter your name and add",r.a.createElement("br",null),"a profile picture."),r.a.createElement(i.a,{id:"registration-first-name",label:"Name",onChange:function(e){t&&a();const{target:n}=e;f(n.value),l(n.value.length>0)},value:d,error:t,autoComplete:"given-name"}),r.a.createElement(i.a,{id:"registration-last-name",label:"Last Name (optional)",onChange:function(e){const{target:t}=e;h(t.value)},value:m,autoComplete:"family-name"}),c&&r.a.createElement(E.a,{type:"submit",ripple:!0,isLoading:e},"Start Messaging"))))}));let y=null;class w{}w.render=function(e,t){y(e,t)},self.QrCreator=w,function(e){function t(t,n,r,a){var o={},c=e(r,n);c.u(t),c.J(),a=a||0;var i=c.h(),l=c.h()+2*a;return o.text=t,o.level=n,o.version=r,o.O=l,o.a=function(e,t){return t-=a,!(0>(e-=a)||e>=i||0>t||t>=i)&&c.a(e,t)},o}function n(e,t,n,r,a,o,c,i,l,u){function s(t,n,r,a,c,i,l){t?(e.lineTo(n+i,r+l),e.arcTo(n,r,a,c,o)):e.lineTo(n,r)}c?e.moveTo(t+o,n):e.moveTo(t,n),s(i,r,n,r,a,-o,0),s(l,r,a,t,a,0,-o),s(u,t,a,t,n,o,0),s(c,t,n,r,n,0,o)}function r(e,t,n,r,a,o,c,i,l,u){function s(t,n,r,a){e.moveTo(t+r,n),e.lineTo(t,n),e.lineTo(t,n+a),e.arcTo(t,n,t+r,n,o)}c&&s(t,n,o,o),i&&s(r,n,-o,o),l&&s(r,a,-o,-o),u&&s(t,a,o,-o)}function a(e,a){e:{var o=a.text,c=a.v,i=a.N,l=a.K,u=a.P;for(i=Math.max(1,i||1),l=Math.min(40,l||40);i<=l;i+=1)try{var s=t(o,c,i,u);break e}catch(e){}s=void 0}if(!s)return null;for(o=e.getContext("2d"),a.background&&(o.fillStyle=a.background,o.fillRect(a.left,a.top,a.size,a.size)),c=s.O,l=a.size/c,o.beginPath(),u=0;uMath.round(e*t.size)),"linear-gradient"===r)var o=e.createLinearGradient.apply(e,n);else{if("radial-gradient"!==r)throw Error("Unsupported fill");o=e.createRadialGradient.apply(e,n)}a.forEach(([e,t])=>{o.addColorStop(e,t)}),e.fillStyle=o}}(o,a),o.fill(),e}var o={minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:.5,quiet:0};y=function(e,t){var n={};Object.assign(n,o,e),n.N=n.minVersion,n.K=n.maxVersion,n.v=n.ecLevel,n.left=n.left,n.top=n.top,n.size=n.size,n.fill=n.fill,n.background=n.background,n.text=n.text,n.R=n.radius,n.P=n.quiet,t instanceof HTMLCanvasElement?(t.width===n.size&&t.height===n.size||(t.width=n.size,t.height=n.size),t.getContext("2d").clearRect(0,0,t.width,t.height),a(t,n)):((e=document.createElement("canvas")).width=n.size,e.height=n.size,n=a(e,n),t.appendChild(n))}}(function(){function e(a,c){function i(e,t){for(var n=-1;7>=n;n+=1)if(!(-1>=e+n||d<=e+n))for(var r=-1;7>=r;r+=1)-1>=t+r||d<=t+r||(s[e+n][t+r]=0<=n&&6>=n&&(0==r||6==r)||0<=r&&6>=r&&(0==n||6==n)||2<=n&&4>=n&&2<=r&&4>=r)}function l(e,n){for(var c=d=4*a+17,l=Array(c),h=0;h=v;v+=1)for(var g=-2;2>=g;g+=1)s[b+v][p+g]=-2==v||2==v||-2==g||2==g||0==v&&0==g}for(c=8;cl;l+=1)h=!e&&1==(c>>l&1),s[6>l?l:8>l?l+1:d-15+l][8]=h,s[8][8>l?d-l-1:9>l?15-l:14-l]=h;if(s[d-8][8]=!e,7<=a){for(c=r.A(a),l=0;18>l;l+=1)h=!e&&1==(c>>l&1),s[Math.floor(l/3)][l%3+d-8-3]=h;for(l=0;18>l;l+=1)h=!e&&1==(c>>l&1),s[l%3+d-8-3][Math.floor(l/3)]=h}if(null==f){for(e=o.I(a,u),c=function(){var e=[],t=0,n={B:function(){return e},c:function(t){return 1==(e[Math.floor(t/8)]>>>7-t%8&1)},put:function(e,t){for(var r=0;r>>t-r-1&1))},f:function(){return t},m:function(n){var r=Math.floor(t/8);e.length<=r&&e.push(0),n&&(e[r]|=128>>>t%8),t+=1}};return n}(),l=0;l8*h)throw Error("code length overflow. ("+c.f()+">"+8*h+")");for(c.f()+4<=8*h&&c.put(0,4);0!=c.f()%8;)c.m(!1);for(;!(c.f()>=8*h)&&(c.put(236,8),!(c.f()>=8*h));)c.put(17,8);var E=0;for(h=l=0,b=Array(e.length),p=Array(e.length),v=0;vv;v+=1)null==s[l][p-v]&&(g=!1,b>>h&1)),n(l,p-v)&&(g=!g),s[l][p-v]=g,-1==--h&&(b+=1,h=7));if(0>(l+=c)||d<=l){l-=c,c=-c;break}}}var u=n[c],s=null,d=0,f=null,m=[],h={u:function(t){t=function(t){var n=e.s(t);return{S:function(){return 4},b:function(){return n.length},write:function(e){for(var t=0;te||d<=e||0>t||d<=t)throw Error(e+","+t);return s[e][t]},h:function(){return d},J:function(){for(var e=0,t=0,n=0;8>n;n+=1){l(!0,n);var a=r.D(h);(0==n||e>a)&&(e=a,t=n)}l(!1,t)}};return h}function t(e,n){if(void 0===e.length)throw Error(e.length+"/"+n);var r=function(){for(var t=0;to.b()-e.b())return o;for(var n=a.g(o.c(0))-a.g(e.c(0)),r=Array(o.b()),c=0;cr?t.push(r):2048>r?t.push(192|r>>6,128|63&r):55296>r||57344<=r?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return t};var n={L:1,M:0,Q:3,H:2},r=function(){function e(e){for(var t=0;0!=e;)t+=1,e>>>=1;return t}var n=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]];return{w:function(t){for(var n=t<<10;0<=e(n)-e(1335);)n^=1335<t||40t?8:16},D:function(e){for(var t=e.h(),n=0,r=0;r=i;i+=1)if(!(0>r+i||t<=r+i))for(var l=-1;1>=l;l+=1)0>a+l||t<=a+l||(0!=i||0!=l)&&c==e.a(r+i,a+l)&&(o+=1);5n;n+=1)e[n]=1<n;n+=1)e[n]=e[n-4]^e[n-5]^e[n-6]^e[n-8];for(n=0;255>n;n+=1)t[e[n]]=n;return{g:function(e){if(1>e)throw Error("glog("+e+")");return t[e]},i:function(t){for(;0>t;)t+=255;for(;256<=t;)t-=255;return e[t]}}}(),o=function(){function e(e,r){switch(r){case n.L:return t[4*(e-1)];case n.M:return t[4*(e-1)+1];case n.Q:return t[4*(e-1)+2];case n.H:return t[4*(e-1)+3]}}var t=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];return{I:function(t,n){var r=e(t,n);if(void 0===r)throw Error("bad rs block @ typeNumber:"+t+"/errorCorrectLevel:"+n);t=r.length/3,n=[];for(var a=0;aObject(c.l)(e,["connectionState","authQrCode"]),(e,t)=>Object(c.l)(t,["returnToAuthPhoneNumber"]))(({connectionState:e,authQrCode:t,returnToAuthPhoneNumber:n})=>{const a=Object(r.q)(null);return Object(r.n)(()=>{if(!t||"connectionStateReady"!==e)return;const n=a.current;n.innerHTML="",n.classList.remove("pre-animate"),k.render({text:"tg://login?token="+t.token,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},n)},[e,t]),h(n),r.a.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},r.a.createElement("div",{className:"auth-form"},r.a.createElement("div",{className:Object(N.a)("qr-container",t&&"pre-animate"),ref:a},!t&&r.a.createElement(l.a,null)),r.a.createElement("h3",null," Log in to Telegram by QR Code"),r.a.createElement("ol",null,r.a.createElement("li",null,r.a.createElement("span",null,"Open Telegram on your phone")),r.a.createElement("li",null,r.a.createElement("span",null,"Go to ",r.a.createElement("b",null,"Settings")," > ",r.a.createElement("b",null,"Devices")," > ",r.a.createElement("b",null,"Scan QR"))),r.a.createElement("li",null,r.a.createElement("span",null,"Point your phone at this screen to confirm login"))),r.a.createElement(E.a,{isText:!0,onClick:n},"Log in by phone number")))}))},94:function(e,t,n){"use strict";var r=n(11),a=n(31),o=n(103);t.a=()=>{const e=Object(a.a)();return Object(o.a)(()=>r.a(e),[e]),r.b}},99:function(e,t,n){"use strict";var r=n(0),a=n(50);var o=n(8),c=n(43),i=n(29),l=n(52),u=n(94),s=n(25),d=n(113);n(140);t.a=e=>{const{title:t,className:n,isOpen:f,header:m,hasCloseButton:h,noBackdrop:b,children:p,onClose:v,onCloseAnimationEnd:g,onEnter:E}=e,{shouldRender:j,transitionClassNames:O}=Object(i.a)(f,g),y=Object(r.q)(null);Object(r.n)(()=>f?Object(a.a)({onEsc:v,onEnter:E}):void 0,[f,v,E]),Object(r.n)(()=>f&&y.current?function(e){function t(t){if("Tab"!==t.key)return;t.preventDefault(),t.stopPropagation();const n=Array.from(e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(!n.length)return;const r=n.findIndex(e=>e.isSameNode(document.activeElement));let a=0;r>=0&&(a=t.shiftKey?r>0?r-1:n.length-1:r{document.removeEventListener("keydown",t,!1)}}(y.current):void 0,[f]),Object(l.a)(([e])=>(document.body.classList.toggle("has-open-dialog",f),(f||!f&&void 0!==e)&&Object(c.b)(200),()=>{document.body.classList.remove("has-open-dialog")}),[f]);const w=Object(u.a)();if(!j)return;const k=Object(o.a)("Modal",n,O,b&&"transparent-backdrop");return r.a.createElement(d.a,null,r.a.createElement("div",{ref:y,className:k,tabIndex:-1,role:"dialog"},r.a.createElement("div",{className:"modal-container"},r.a.createElement("div",{className:"modal-backdrop",onClick:v}),r.a.createElement("div",{className:"modal-dialog"},m||(t?r.a.createElement("div",{className:"modal-header"},h&&r.a.createElement(s.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:w("Close"),onClick:v},r.a.createElement("i",{className:"icon-close"})),r.a.createElement("div",{className:"modal-title"},t)):void 0),r.a.createElement("div",{className:"modal-content custom-scroll"},p)))))}}}]); +//# sourceMappingURL=4.3009ada641e67eb52367.js.map \ No newline at end of file diff --git a/dist/4.dbb569ca042ea30048a3.js.map b/dist/4.3009ada641e67eb52367.js.map similarity index 99% rename from dist/4.dbb569ca042ea30048a3.js.map rename to dist/4.3009ada641e67eb52367.js.map index 3f060ec5..25e2d41f 100644 --- a/dist/4.dbb569ca042ea30048a3.js.map +++ b/dist/4.3009ada641e67eb52367.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///./src/hooks/useOnChange.ts","webpack:///./src/components/common/AnimatedSticker.tsx","webpack:///./src/components/ui/Portal.ts","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/hooks/useBackgroundMode.ts","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx","webpack:///./src/components/common/TrackingMonkey.tsx","webpack:///./src/hooks/useHistoryBack.ts","webpack:///./src/components/auth/AuthCode.tsx","webpack:///./src/components/auth/AuthPassword.tsx","webpack:///./src/components/auth/AuthRegister.tsx","webpack:///./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack:///./src/components/auth/AuthQrCode.tsx","webpack:///./src/hooks/useLang.ts","webpack:///./src/components/ui/Modal.tsx","webpack:///./src/util/trapFocus.ts"],"names":["cb","dependencies","prevDeps","usePrevious","some","d","i","lottiePromise","RLottie","async","ensureLottie","default","setTimeout","memo","className","id","animationData","play","playSegment","speed","noLoop","size","quality","isLowPriority","onLoad","animation","setAnimation","useState","container","useRef","wasPlaying","isFrozen","playRef","current","playSegmentRef","useEffect","exec","newAnimation","setSpeed","then","fastRaf","destroy","playAnimation","useCallback","shouldRestart","goToAndPlay","pauseAnimation","pause","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","useHeavyAnimationCheck","useBackgroundMode","fullClassName","buildClassName","IS_IOS","style","undefined","ref","Portal","containerId","children","elementRef","document","createElement","useLayoutEffect","querySelector","element","classList","add","appendChild","TeactDOM","render","removeChild","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","getAnimationData","name","path","replace","window","location","origin","mediaLoader","ApiMediaFormat","Lottie","cropperResultOptions","type","format","circle","Croppie","croppiePromise","cropper","file","onChange","onClose","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","getElementById","offsetWidth","offsetHeight","enableZoom","boundary","width","height","viewport","dataUri","blobToDataUri","bind","url","err","DEBUG","console","error","initCropper","ensureCroppie","lang","useLang","Modal","isOpen","Boolean","title","hasCloseButton","Loading","Button","round","color","onClick","result","croppedImg","blobToFile","ariaLabel","disabled","currentAvatarBlobUrl","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","role","tabIndex","event","target","files","value","accept","src","alt","URL","revokeObjectURL","createObjectURL","onBlur","onFocus","hasFocus","addEventListener","removeEventListener","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","IS_MOBILE_SCREEN","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","isPasswordVisible","isBig","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","FOCUS_DELAY_TIMEOUT_MS","isLoading","hint","placeholder","submitLabel","clearError","onChangePasswordVisibility","onInputChange","onSubmit","inputRef","password","setPassword","canSubmit","setCanSubmit","IS_TOUCH_ENV","focus","requestAnimationFrame","select","action","preventDefault","autoComplete","e","length","MIN_PASSWORD_LENGTH","ripple","code","codeLength","trackingDirection","isTracking","idleMonkeyData","setIdleMonkeyData","trackingMonkeyData","setTrackingMonkeyData","TRACKING_FRAMES_PER_SYMBOL","AnimatedSticker","startFrame","endFrame","getTrackingFrames","useHistoryBack","handler","handlePopState","history","pushState","back","withGlobal","global","pick","setGlobal","actions","authPhoneNumber","authIsCodeViaApp","authIsLoading","authError","setAuthCode","returnToAuthPhoneNumber","clearAuthError","setCode","setIsTracking","setTrackingDirection","onCodeChange","currentTarget","substr","InputText","label","onInput","inputMode","authHint","setAuthPassword","showPassword","setShowPassword","handleChangePasswordVisibility","isVisible","handleSubmit","PasswordForm","signUp","uploadProfilePhoto","isButtonShown","setIsButtonShown","croppedFile","setCroppedFile","firstName","setFirstName","lastName","setLastName","method","AvatarEditable","G","H","w","B","self","QrCreator","t","c","a","b","h","u","J","r","text","level","version","O","C","g","x","f","lineTo","arcTo","moveTo","z","y","v","N","K","P","Math","max","min","getContext","background","fillStyle","fillRect","left","top","beginPath","p","q","k","m","D","E","n","l","floor","R","I","F","fill","colorStops","position","map","createLinearGradient","apply","Error","createRadialGradient","forEach","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","Object","assign","HTMLCanvasElement","clearRect","Array","put","push","write","j","o","s","S","multiply","charCodeAt","L","M","Q","abs","connectionState","authQrCode","qrCodeRef","innerHTML","remove","token","isText","forceUpdate","useForceUpdate","useOnChange","langProvider","props","header","noBackdrop","onCloseAnimationEnd","onEnter","shouldRender","transitionClassNames","useShowTransition","modalRef","captureKeyboardListeners","onEsc","handleKeyDown","key","stopPropagation","focusableElements","from","querySelectorAll","currentFocusedIndex","findIndex","em","isSameNode","activeElement","newFocusedIndex","shiftKey","trapFocus","useEffectWithPrevDeps","prevIsOpen","body","toggle","dispatchHeavyAnimationEvent"],"mappings":"0FAAA,YAEe,KAA0BA,EAAwBC,KAC/D,MAAMC,EAAWC,YAAeF,GAC3BC,IAAYD,EAAaG,KAAK,CAACC,EAAGC,IAAMD,IAAMH,EAASI,KAE1DN,EAAGE,GAAY,M,iCCNnB,iDA0BA,IAAIK,EACAC,EAKJC,eAAeC,IAMb,OALKH,IACHA,EAAgB,8BAChBC,SAAiBD,GAAsBI,SAGlCJ,EAGTK,WAAWF,EAXe,KAqLXG,gBAxKuB,EACpCC,YACAC,KACAC,gBACAC,OACAC,cACAC,QACAC,SACAC,OACAC,UACAC,gBACAC,aAEA,MAAOC,EAAWC,GAAgBC,cAE5BC,EAAYC,YAAuB,MACnCC,EAAaD,aAAO,GACpBE,EAAWF,aAAO,GAElBG,EAAUH,cAChBG,EAAQC,QAAUhB,EAClB,MAAMiB,EAAiBL,cACvBK,EAAeD,QAAUf,EAEzBiB,YAAU,KACR,GAAIV,IAAcT,EAChB,OAGF,MAAMoB,EAAO,KACX,IAAKR,EAAUK,QACb,OAGF,MAAMI,EAAe,IAAI7B,EACvBO,EACAa,EAAUK,QACVjB,EACA,CACEI,SACAC,OACAC,UACAC,iBAEFC,GAGEL,GACFkB,EAAaC,SA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O,qBAEhC,CAACzO,IAEJ,MAAMH,EAAOC,cAEb,IAAKuP,EACH,OA8BF,MAAM/T,EAAgBC,YACpB,QACAzC,EACAwW,EACAJ,GAAc,wBAGhB,OACE,kBAACtT,EAAA,EAAD,KACE,yBACED,IAAK6T,EACL1W,UAAWwC,EACX+F,UAAW,EACXD,KAAK,UAEL,yBAAKtI,UAAU,mBACb,yBAAKA,UAAU,iBAAiB0H,QAASlC,IACzC,yBAAKxF,UAAU,gBA3CjBmW,IAIC/O,EAKH,yBAAKpH,UAAU,gBACZqH,GACC,kBAACE,EAAA,EAAD,CACEC,OAAK,EACLC,MAAM,cACNlH,KAAK,UACLuH,UAAWf,EAAK,SAChBW,QAASlC,GAET,uBAAGxF,UAAU,gBAGjB,yBAAKA,UAAU,eAAeoH,SAjBlC,GAyCQ,yBAAKpH,UAAU,+BACZgD","file":"4.dbb569ca042ea30048a3.js","sourcesContent":["import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import React, {\n FC, useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_IOS } from '../../util/environment';\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\ntype OwnProps = {\n className?: string;\n id: string;\n animationData: AnyLiteral;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n onLoad?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise;\nlet RLottie: RLottieClass;\n\n// Time supposed for judges to measure \"Transferred Size\" in Dev Tools\nconst LOTTIE_LOAD_DELAY = 5000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC = ({\n className,\n id,\n animationData,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n onLoad,\n}) => {\n const [animation, setAnimation] = useState();\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !animationData) {\n return;\n }\n\n const exec = () => {\n if (!container.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n id,\n container.current,\n animationData,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (container.current) {\n exec();\n }\n });\n });\n }\n }, [animation, animationData, id, isLowPriority, noLoop, onLoad, quality, size, speed]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else if (shouldRestart) {\n animation.goToAndPlay(0);\n } else {\n animation.play();\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation();\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n const fullClassName = buildClassName(\n 'AnimatedSticker',\n className,\n // Workaround for an iOS bug when animated stickers sometimes disappear\n IS_IOS && play && 'is-playing',\n );\n\n const style = size ? `width: ${size}px; height: ${size}px;` : undefined;\n\n return (\n \n );\n};\n\nexport default memo(AnimatedSticker);\n","import { FC, useRef, useLayoutEffect } from '../../lib/teact/teact';\nimport TeactDOM from '../../lib/teact/teact-dom';\n\ntype OwnProps = {\n containerId?: string;\n className?: string;\n children: any;\n};\n\nconst Portal: FC = ({ containerId, className, children }) => {\n const elementRef = useRef(document.createElement('div'));\n\n useLayoutEffect(() => {\n const container = document.querySelector(containerId || '#portals');\n if (!container) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (className) {\n element.classList.add(className);\n }\n\n container.appendChild(element);\n\n return () => {\n TeactDOM.render(undefined, element);\n container.removeChild(element);\n };\n }, [className, containerId]);\n\n return TeactDOM.render(children, elementRef.current);\n};\n\nexport default Portal;\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import { useEffect } from '../lib/teact/teact';\n\nexport default (\n onBlur: AnyToVoidFunction,\n onFocus: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (!document.hasFocus()) {\n onBlur();\n }\n\n window.addEventListener('blur', onBlur);\n window.addEventListener('focus', onFocus);\n\n return () => {\n window.removeEventListener('focus', onFocus);\n window.removeEventListener('blur', onBlur);\n };\n }, [onBlur, onFocus]);\n};\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n
\n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n code: string;\n codeLength: number;\n trackingDirection: number;\n isTracking: boolean;\n isBig?: boolean;\n};\n\nconst TRACKING_START_FRAME = 15;\nconst TRACKING_END_FRAME = 180;\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst TrackingMonkey: FC = ({\n code,\n codeLength,\n trackingDirection,\n isTracking,\n isBig,\n}) => {\n const [idleMonkeyData, setIdleMonkeyData] = useState>();\n const [trackingMonkeyData, setTrackingMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const TRACKING_FRAMES_PER_SYMBOL = (TRACKING_END_FRAME - TRACKING_START_FRAME) / codeLength;\n\n useEffect(() => {\n if (!idleMonkeyData) {\n getAnimationData('MonkeyIdle').then(setIdleMonkeyData);\n }\n }, [idleMonkeyData]);\n\n useEffect(() => {\n if (!trackingMonkeyData) {\n getAnimationData('MonkeyTracking').then(setTrackingMonkeyData);\n }\n }, [trackingMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n function getTrackingFrames(): [number, number] {\n const startFrame = (code && code.length > 1) || trackingDirection < 0\n ? TRACKING_START_FRAME + TRACKING_FRAMES_PER_SYMBOL * (code.length - 1)\n : 0;\n const endFrame = code.length === codeLength\n ? TRACKING_END_FRAME\n : TRACKING_START_FRAME + TRACKING_FRAMES_PER_SYMBOL * code.length;\n\n if (trackingDirection < 1) {\n return [\n endFrame,\n startFrame,\n ];\n }\n\n return [\n startFrame,\n endFrame,\n ];\n }\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {idleMonkeyData && (\n \n )}\n {trackingMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(TrackingMonkey);\n","// This is unsafe and can be not chained as `popstate` event is asynchronous\n\nexport default function useHistoryBack(handler: NoneToVoidFunction) {\n function handlePopState() {\n handler();\n }\n\n window.addEventListener('popstate', handlePopState);\n window.history.pushState({}, '');\n\n return () => {\n window.removeEventListener('popstate', handlePopState);\n window.history.back();\n };\n}\n","import { FormEvent } from 'react';\nimport React, {\n FC, useState, useEffect, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\n\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport TrackingMonkey from '../common/TrackingMonkey';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst CODE_LENGTH = 5;\n\nconst AuthCode: FC = ({\n authPhoneNumber, authIsCodeViaApp, authIsLoading, authError, setAuthCode, returnToAuthPhoneNumber, clearAuthError,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [code, setCode] = useState('');\n const [isTracking, setIsTracking] = useState(false);\n const [trackingDirection, setTrackingDirection] = useState(1);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, []);\n\n useHistoryBack(returnToAuthPhoneNumber);\n\n const onCodeChange = useCallback((e: FormEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n const { currentTarget: target } = e;\n target.value = target.value.replace(/[^\\d]+/, '').substr(0, CODE_LENGTH);\n\n if (target.value === code) {\n return;\n }\n\n setCode(target.value);\n\n if (!isTracking) {\n setIsTracking(true);\n } else if (!target.value.length) {\n setIsTracking(false);\n }\n\n if (code && code.length > target.value.length) {\n setTrackingDirection(-1);\n } else {\n setTrackingDirection(1);\n }\n\n if (target.value.length === CODE_LENGTH) {\n setAuthCode({ code: target.value });\n }\n }, [authError, clearAuthError, code, isTracking, setAuthCode]);\n\n return (\n
\n
\n \n

\n {authPhoneNumber}\n \n \n

\n \n

\n {authIsCodeViaApp ? (\n <>\n We have sent the code to the Telegram app\n
on your other device.\n \n ) : (\n <>\n We have sent you an SMS\n
with the code.\n \n )}\n

\n \n {authIsLoading && }\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authPhoneNumber', 'authIsCodeViaApp', 'authIsLoading', 'authError']),\n (setGlobal, actions): DispatchProps => pick(actions, ['setAuthCode', 'returnToAuthPhoneNumber', 'clearAuthError']),\n)(AuthCode));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport MonkeyPassword from '../common/PasswordMonkey';\nimport PasswordForm from '../common/PasswordForm';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst AuthPassword: FC = ({\n authIsLoading, authError, authHint, setAuthPassword, clearAuthError,\n}) => {\n const [showPassword, setShowPassword] = useState(false);\n\n const handleChangePasswordVisibility = useCallback((isVisible) => {\n setShowPassword(isVisible);\n }, []);\n\n const handleSubmit = useCallback((password: string) => {\n setAuthPassword({ password });\n }, [setAuthPassword]);\n\n return (\n
\n
\n \n

Enter Your Password

\n

\n Your account is protected with\n
an additional password.\n

\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authIsLoading', 'authError', 'authHint']),\n (setGlobal, actions): DispatchProps => pick(actions, ['setAuthPassword', 'clearAuthError']),\n)(AuthPassword));\n","import { ChangeEvent } from 'react';\nimport React, { FC, useState, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport Button from '../ui/Button';\nimport InputText from '../ui/InputText';\nimport AvatarEditable from '../ui/AvatarEditable';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst AuthRegister: FC = ({\n authIsLoading, authError, signUp, clearAuthError, uploadProfilePhoto,\n}) => {\n const [isButtonShown, setIsButtonShown] = useState(false);\n const [croppedFile, setCroppedFile] = useState();\n const [firstName, setFirstName] = useState('');\n const [lastName, setLastName] = useState('');\n\n function handleFirstNameChange(event: ChangeEvent) {\n if (authError) {\n clearAuthError();\n }\n\n const { target } = event;\n\n setFirstName(target.value);\n setIsButtonShown(target.value.length > 0);\n }\n\n function handleLastNameChange(event: ChangeEvent) {\n const { target } = event;\n\n setLastName(target.value);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n signUp({ firstName, lastName });\n\n if (croppedFile) {\n uploadProfilePhoto({ file: croppedFile });\n }\n }\n\n return (\n
\n
\n
\n \n

Your Name

\n

\n Enter your name and add\n
a profile picture.\n

\n \n \n {isButtonShown && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authIsLoading', 'authError']),\n (setGlobal, actions): DispatchProps => pick(actions, ['signUp', 'clearAuthError', 'uploadProfilePhoto']),\n)(AuthRegister));\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r>>7-b%8&1)},put:function(b,h){for(var a=0;a>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;fk;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;nn;n+=1)null==r[k][q-n]&&(l=!1,p>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;bb.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;gb?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<a||40a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5e;e+=1)c[e]=1<e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d;\ntype DispatchProps = Pick;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState, authQrCode, returnToAuthPhoneNumber,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef(null);\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n useHistoryBack(returnToAuthPhoneNumber);\n\n return (\n
\n
\n
\n {!authQrCode && }\n
\n

Log in to Telegram by QR Code

\n
    \n
  1. Open Telegram on your phone
  2. \n
  3. Go to Settings > Devices > Scan QR
  4. \n
  5. Point your phone at this screen to confirm login
  6. \n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['connectionState', 'authQrCode']),\n (setGlobal, actions): DispatchProps => pick(actions, ['returnToAuthPhoneNumber']),\n)(AuthCode));\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport trapFocus from '../../util/trapFocus';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Portal from './Portal';\n\nimport './Modal.scss';\n\nconst ANIMATION_DURATION = 200;\n\ntype OwnProps = {\n title?: string;\n className?: string;\n isOpen?: boolean;\n header?: FC;\n hasCloseButton?: boolean;\n noBackdrop?: boolean;\n children: any;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onEnter?: () => void;\n};\n\nconst Modal: FC = (props) => {\n const {\n title,\n className,\n isOpen,\n header,\n hasCloseButton,\n noBackdrop,\n children,\n onClose,\n onCloseAnimationEnd,\n onEnter,\n } = props;\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n // eslint-disable-next-line no-null/no-null\n const modalRef = useRef(null);\n\n useEffect(() => (isOpen\n ? captureKeyboardListeners({ onEsc: onClose, onEnter })\n : undefined), [isOpen, onClose, onEnter]);\n useEffect(() => (isOpen && modalRef.current ? trapFocus(modalRef.current) : undefined), [isOpen]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n document.body.classList.toggle('has-open-dialog', isOpen);\n\n if (isOpen || (!isOpen && prevIsOpen !== undefined)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n\n return () => {\n document.body.classList.remove('has-open-dialog');\n };\n }, [isOpen]);\n\n const lang = useLang();\n\n if (!shouldRender) {\n return undefined;\n }\n\n function renderHeader() {\n if (header) {\n return header;\n }\n\n if (!title) {\n return undefined;\n }\n\n return (\n
\n {hasCloseButton && (\n \n \n \n )}\n
{title}
\n
\n );\n }\n\n const fullClassName = buildClassName(\n 'Modal',\n className,\n transitionClassNames,\n noBackdrop && 'transparent-backdrop',\n );\n\n return (\n \n \n
\n
\n
\n {renderHeader()}\n
\n {children}\n
\n
\n
\n
\n
\n );\n};\n\nexport default Modal;\n","export default function trapFocus(element: HTMLElement) {\n function handleKeyDown(e: KeyboardEvent) {\n if (e.key !== 'Tab') {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n const focusableElements = Array.from(\n element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'),\n ) as HTMLElement[];\n if (!focusableElements.length) {\n return;\n }\n\n const currentFocusedIndex = focusableElements.findIndex((em) => em.isSameNode(document.activeElement));\n let newFocusedIndex = 0;\n if (currentFocusedIndex >= 0) {\n if (e.shiftKey) {\n newFocusedIndex = currentFocusedIndex > 0\n ? currentFocusedIndex - 1\n : focusableElements.length - 1;\n } else {\n newFocusedIndex = currentFocusedIndex < focusableElements.length - 1\n ? currentFocusedIndex + 1\n : 0;\n }\n }\n\n focusableElements[newFocusedIndex].focus();\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///./src/hooks/useOnChange.ts","webpack:///./src/components/common/AnimatedSticker.tsx","webpack:///./src/components/ui/Portal.ts","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/hooks/useBackgroundMode.ts","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx","webpack:///./src/components/common/TrackingMonkey.tsx","webpack:///./src/hooks/useHistoryBack.ts","webpack:///./src/components/auth/AuthCode.tsx","webpack:///./src/components/auth/AuthPassword.tsx","webpack:///./src/components/auth/AuthRegister.tsx","webpack:///./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack:///./src/components/auth/AuthQrCode.tsx","webpack:///./src/hooks/useLang.ts","webpack:///./src/components/ui/Modal.tsx","webpack:///./src/util/trapFocus.ts"],"names":["cb","dependencies","prevDeps","usePrevious","some","d","i","lottiePromise","RLottie","async","ensureLottie","default","setTimeout","memo","className","id","animationData","play","playSegment","speed","noLoop","size","quality","isLowPriority","onLoad","animation","setAnimation","useState","container","useRef","wasPlaying","isFrozen","playRef","current","playSegmentRef","useEffect","exec","newAnimation","setSpeed","then","fastRaf","destroy","playAnimation","useCallback","shouldRestart","goToAndPlay","pauseAnimation","pause","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","useHeavyAnimationCheck","useBackgroundMode","fullClassName","buildClassName","IS_IOS","style","undefined","ref","Portal","containerId","children","elementRef","document","createElement","useLayoutEffect","querySelector","element","classList","add","appendChild","TeactDOM","render","removeChild","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","getAnimationData","name","path","replace","window","location","origin","mediaLoader","ApiMediaFormat","Lottie","cropperResultOptions","type","format","circle","Croppie","croppiePromise","cropper","file","onChange","onClose","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","getElementById","offsetWidth","offsetHeight","enableZoom","boundary","width","height","viewport","dataUri","blobToDataUri","bind","url","err","DEBUG","console","error","initCropper","ensureCroppie","lang","useLang","Modal","isOpen","Boolean","title","hasCloseButton","Loading","Button","round","color","onClick","result","croppedImg","blobToFile","ariaLabel","disabled","currentAvatarBlobUrl","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","role","tabIndex","event","target","files","value","accept","src","alt","URL","revokeObjectURL","createObjectURL","onBlur","onFocus","hasFocus","addEventListener","removeEventListener","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","IS_MOBILE_SCREEN","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","isPasswordVisible","isBig","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","FOCUS_DELAY_TIMEOUT_MS","isLoading","hint","placeholder","submitLabel","clearError","onChangePasswordVisibility","onInputChange","onSubmit","inputRef","password","setPassword","canSubmit","setCanSubmit","IS_TOUCH_ENV","focus","requestAnimationFrame","select","action","preventDefault","autoComplete","e","length","MIN_PASSWORD_LENGTH","ripple","code","codeLength","trackingDirection","isTracking","idleMonkeyData","setIdleMonkeyData","trackingMonkeyData","setTrackingMonkeyData","TRACKING_FRAMES_PER_SYMBOL","AnimatedSticker","startFrame","endFrame","getTrackingFrames","useHistoryBack","handler","handlePopState","history","pushState","back","withGlobal","global","pick","setGlobal","actions","authPhoneNumber","authIsCodeViaApp","authIsLoading","authError","setAuthCode","returnToAuthPhoneNumber","clearAuthError","setCode","setIsTracking","setTrackingDirection","onCodeChange","currentTarget","substr","InputText","label","onInput","inputMode","authHint","setAuthPassword","showPassword","setShowPassword","handleChangePasswordVisibility","isVisible","handleSubmit","PasswordForm","signUp","uploadProfilePhoto","isButtonShown","setIsButtonShown","croppedFile","setCroppedFile","firstName","setFirstName","lastName","setLastName","method","AvatarEditable","G","H","w","B","self","QrCreator","t","c","a","b","h","u","J","r","text","level","version","O","C","g","x","f","lineTo","arcTo","moveTo","z","y","v","N","K","P","Math","max","min","getContext","background","fillStyle","fillRect","left","top","beginPath","p","q","k","m","D","E","n","l","floor","R","I","F","fill","colorStops","position","map","createLinearGradient","apply","Error","createRadialGradient","forEach","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","Object","assign","HTMLCanvasElement","clearRect","Array","put","push","write","j","o","s","S","multiply","charCodeAt","L","M","Q","abs","connectionState","authQrCode","qrCodeRef","innerHTML","remove","token","isText","forceUpdate","useForceUpdate","useOnChange","langProvider","props","header","noBackdrop","onCloseAnimationEnd","onEnter","shouldRender","transitionClassNames","useShowTransition","modalRef","captureKeyboardListeners","onEsc","handleKeyDown","key","stopPropagation","focusableElements","from","querySelectorAll","currentFocusedIndex","findIndex","em","isSameNode","activeElement","newFocusedIndex","shiftKey","trapFocus","useEffectWithPrevDeps","prevIsOpen","body","toggle","dispatchHeavyAnimationEvent"],"mappings":"0FAAA,YAEe,KAA0BA,EAAwBC,KAC/D,MAAMC,EAAWC,YAAeF,GAC3BC,IAAYD,EAAaG,KAAK,CAACC,EAAGC,IAAMD,IA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AC9B3T,EAAQ4T,iBAAiB,6EAE3B,IAAKF,EAAkBhL,OACrB,OAGF,MAAMmL,EAAsBH,EAAkBI,UAAWC,GAAOA,EAAGC,WAAWpU,SAASqU,gBACvF,IAAIC,EAAkB,EAClBL,GAAuB,IAEvBK,EADEzL,EAAE0L,SACcN,EAAsB,EACpCA,EAAsB,EACtBH,EAAkBhL,OAAS,EAEbmL,EAAsBH,EAAkBhL,OAAS,EAC/DmL,EAAsB,EACtB,GAIRH,EAAkBQ,GAAiB/L,QAKrC,OAFAvI,SAASmG,iBAAiB,UAAWwN,GAAe,GAE7C,KACL3T,SAASoG,oBAAoB,UAAWuN,GAAe,IDcXa,CAAUhB,EAASvV,cAAWyB,EAAY,CAACsE,IAEzFyQ,YAAsB,EAAEC,MACtB1U,SAAS2U,KAAKtU,UAAUuU,OAAO,kBAAmB5Q,IAE9CA,IAAYA,QAAyBtE,IAAfgV,IACxBG,YAzCqB,KA4ChB,KACL7U,SAAS2U,KAAKtU,UAAUoS,OAAO,qBAEhC,CAACzO,IAEJ,MAAMH,EAAOC,cAEb,IAAKuP,EACH,OA8BF,MAAM/T,EAAgBC,YACpB,QACAzC,EACAwW,EACAJ,GAAc,wBAGhB,OACE,kBAACtT,EAAA,EAAD,KACE,yBACED,IAAK6T,EACL1W,UAAWwC,EACX+F,UAAW,EACXD,KAAK,UAEL,yBAAKtI,UAAU,mBACb,yBAAKA,UAAU,iBAAiB0H,QAASlC,IACzC,yBAAKxF,UAAU,gBA3CjBmW,IAIC/O,EAKH,yBAAKpH,UAAU,gBACZqH,GACC,kBAACE,EAAA,EAAD,CACEC,OAAK,EACLC,MAAM,cACNlH,KAAK,UACLuH,UAAWf,EAAK,SAChBW,QAASlC,GAET,uBAAGxF,UAAU,gBAGjB,yBAAKA,UAAU,eAAeoH,SAjBlC,GAyCQ,yBAAKpH,UAAU,+BACZgD","file":"4.3009ada641e67eb52367.js","sourcesContent":["import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import React, {\n FC, useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_IOS } from '../../util/environment';\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\ntype OwnProps = {\n className?: string;\n id: string;\n animationData: AnyLiteral;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n onLoad?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise;\nlet RLottie: RLottieClass;\n\n// Time supposed for judges to measure \"Transferred Size\" in Dev Tools\nconst LOTTIE_LOAD_DELAY = 5000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC = ({\n className,\n id,\n animationData,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n onLoad,\n}) => {\n const [animation, setAnimation] = useState();\n // eslint-disable-next-line no-null/no-null\n const container = useRef(null);\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !animationData) {\n return;\n }\n\n const exec = () => {\n if (!container.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n id,\n container.current,\n animationData,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (container.current) {\n exec();\n }\n });\n });\n }\n }, [animation, animationData, id, isLowPriority, noLoop, onLoad, quality, size, speed]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else if (shouldRestart) {\n animation.goToAndPlay(0);\n } else {\n animation.play();\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation();\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n const fullClassName = buildClassName(\n 'AnimatedSticker',\n className,\n // Workaround for an iOS bug when animated stickers sometimes disappear\n IS_IOS && play && 'is-playing',\n );\n\n const style = size ? `width: ${size}px; height: ${size}px;` : undefined;\n\n return (\n \n );\n};\n\nexport default memo(AnimatedSticker);\n","import { FC, useRef, useLayoutEffect } from '../../lib/teact/teact';\nimport TeactDOM from '../../lib/teact/teact-dom';\n\ntype OwnProps = {\n containerId?: string;\n className?: string;\n children: any;\n};\n\nconst Portal: FC = ({ containerId, className, children }) => {\n const elementRef = useRef(document.createElement('div'));\n\n useLayoutEffect(() => {\n const container = document.querySelector(containerId || '#portals');\n if (!container) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (className) {\n element.classList.add(className);\n }\n\n container.appendChild(element);\n\n return () => {\n TeactDOM.render(undefined, element);\n container.removeChild(element);\n };\n }, [className, containerId]);\n\n return TeactDOM.render(children, elementRef.current);\n};\n\nexport default Portal;\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import { useEffect } from '../lib/teact/teact';\n\nexport default (\n onBlur: AnyToVoidFunction,\n onFocus: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (!document.hasFocus()) {\n onBlur();\n }\n\n window.addEventListener('blur', onBlur);\n window.addEventListener('focus', onFocus);\n\n return () => {\n window.removeEventListener('focus', onFocus);\n window.removeEventListener('blur', onBlur);\n };\n }, [onBlur, onFocus]);\n};\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n
\n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n code: string;\n codeLength: number;\n trackingDirection: number;\n isTracking: boolean;\n isBig?: boolean;\n};\n\nconst TRACKING_START_FRAME = 15;\nconst TRACKING_END_FRAME = 180;\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst TrackingMonkey: FC = ({\n code,\n codeLength,\n trackingDirection,\n isTracking,\n isBig,\n}) => {\n const [idleMonkeyData, setIdleMonkeyData] = useState>();\n const [trackingMonkeyData, setTrackingMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const TRACKING_FRAMES_PER_SYMBOL = (TRACKING_END_FRAME - TRACKING_START_FRAME) / codeLength;\n\n useEffect(() => {\n if (!idleMonkeyData) {\n getAnimationData('MonkeyIdle').then(setIdleMonkeyData);\n }\n }, [idleMonkeyData]);\n\n useEffect(() => {\n if (!trackingMonkeyData) {\n getAnimationData('MonkeyTracking').then(setTrackingMonkeyData);\n }\n }, [trackingMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n function getTrackingFrames(): [number, number] {\n const startFrame = (code && code.length > 1) || trackingDirection < 0\n ? TRACKING_START_FRAME + TRACKING_FRAMES_PER_SYMBOL * (code.length - 1)\n : 0;\n const endFrame = code.length === codeLength\n ? TRACKING_END_FRAME\n : TRACKING_START_FRAME + TRACKING_FRAMES_PER_SYMBOL * code.length;\n\n if (trackingDirection < 1) {\n return [\n endFrame,\n startFrame,\n ];\n }\n\n return [\n startFrame,\n endFrame,\n ];\n }\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {idleMonkeyData && (\n \n )}\n {trackingMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(TrackingMonkey);\n","// This is unsafe and can be not chained as `popstate` event is asynchronous\n\nexport default function useHistoryBack(handler: NoneToVoidFunction) {\n function handlePopState() {\n handler();\n }\n\n window.addEventListener('popstate', handlePopState);\n window.history.pushState({}, '');\n\n return () => {\n window.removeEventListener('popstate', handlePopState);\n window.history.back();\n };\n}\n","import { FormEvent } from 'react';\nimport React, {\n FC, useState, useEffect, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\n\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport TrackingMonkey from '../common/TrackingMonkey';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst CODE_LENGTH = 5;\n\nconst AuthCode: FC = ({\n authPhoneNumber, authIsCodeViaApp, authIsLoading, authError, setAuthCode, returnToAuthPhoneNumber, clearAuthError,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [code, setCode] = useState('');\n const [isTracking, setIsTracking] = useState(false);\n const [trackingDirection, setTrackingDirection] = useState(1);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, []);\n\n useHistoryBack(returnToAuthPhoneNumber);\n\n const onCodeChange = useCallback((e: FormEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n const { currentTarget: target } = e;\n target.value = target.value.replace(/[^\\d]+/, '').substr(0, CODE_LENGTH);\n\n if (target.value === code) {\n return;\n }\n\n setCode(target.value);\n\n if (!isTracking) {\n setIsTracking(true);\n } else if (!target.value.length) {\n setIsTracking(false);\n }\n\n if (code && code.length > target.value.length) {\n setTrackingDirection(-1);\n } else {\n setTrackingDirection(1);\n }\n\n if (target.value.length === CODE_LENGTH) {\n setAuthCode({ code: target.value });\n }\n }, [authError, clearAuthError, code, isTracking, setAuthCode]);\n\n return (\n
\n
\n \n

\n {authPhoneNumber}\n \n \n

\n \n

\n {authIsCodeViaApp ? (\n <>\n We have sent the code to the Telegram app\n
on your other device.\n \n ) : (\n <>\n We have sent you an SMS\n
with the code.\n \n )}\n

\n \n {authIsLoading && }\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authPhoneNumber', 'authIsCodeViaApp', 'authIsLoading', 'authError']),\n (setGlobal, actions): DispatchProps => pick(actions, ['setAuthCode', 'returnToAuthPhoneNumber', 'clearAuthError']),\n)(AuthCode));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport MonkeyPassword from '../common/PasswordMonkey';\nimport PasswordForm from '../common/PasswordForm';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst AuthPassword: FC = ({\n authIsLoading, authError, authHint, setAuthPassword, clearAuthError,\n}) => {\n const [showPassword, setShowPassword] = useState(false);\n\n const handleChangePasswordVisibility = useCallback((isVisible) => {\n setShowPassword(isVisible);\n }, []);\n\n const handleSubmit = useCallback((password: string) => {\n setAuthPassword({ password });\n }, [setAuthPassword]);\n\n return (\n
\n
\n \n

Enter Your Password

\n

\n Your account is protected with\n
an additional password.\n

\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authIsLoading', 'authError', 'authHint']),\n (setGlobal, actions): DispatchProps => pick(actions, ['setAuthPassword', 'clearAuthError']),\n)(AuthPassword));\n","import { ChangeEvent } from 'react';\nimport React, { FC, useState, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport Button from '../ui/Button';\nimport InputText from '../ui/InputText';\nimport AvatarEditable from '../ui/AvatarEditable';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst AuthRegister: FC = ({\n authIsLoading, authError, signUp, clearAuthError, uploadProfilePhoto,\n}) => {\n const [isButtonShown, setIsButtonShown] = useState(false);\n const [croppedFile, setCroppedFile] = useState();\n const [firstName, setFirstName] = useState('');\n const [lastName, setLastName] = useState('');\n\n function handleFirstNameChange(event: ChangeEvent) {\n if (authError) {\n clearAuthError();\n }\n\n const { target } = event;\n\n setFirstName(target.value);\n setIsButtonShown(target.value.length > 0);\n }\n\n function handleLastNameChange(event: ChangeEvent) {\n const { target } = event;\n\n setLastName(target.value);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n signUp({ firstName, lastName });\n\n if (croppedFile) {\n uploadProfilePhoto({ file: croppedFile });\n }\n }\n\n return (\n
\n
\n
\n \n

Your Name

\n

\n Enter your name and add\n
a profile picture.\n

\n \n \n {isButtonShown && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authIsLoading', 'authError']),\n (setGlobal, actions): DispatchProps => pick(actions, ['signUp', 'clearAuthError', 'uploadProfilePhoto']),\n)(AuthRegister));\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r>>7-b%8&1)},put:function(b,h){for(var a=0;a>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;fk;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;nn;n+=1)null==r[k][q-n]&&(l=!1,p>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;bb.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;gb?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<a||40a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5e;e+=1)c[e]=1<e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d;\ntype DispatchProps = Pick;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState, authQrCode, returnToAuthPhoneNumber,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef(null);\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n useHistoryBack(returnToAuthPhoneNumber);\n\n return (\n
\n
\n
\n {!authQrCode && }\n
\n

Log in to Telegram by QR Code

\n
    \n
  1. Open Telegram on your phone
  2. \n
  3. Go to Settings > Devices > Scan QR
  4. \n
  5. Point your phone at this screen to confirm login
  6. \n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['connectionState', 'authQrCode']),\n (setGlobal, actions): DispatchProps => pick(actions, ['returnToAuthPhoneNumber']),\n)(AuthCode));\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport trapFocus from '../../util/trapFocus';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Portal from './Portal';\n\nimport './Modal.scss';\n\nconst ANIMATION_DURATION = 200;\n\ntype OwnProps = {\n title?: string;\n className?: string;\n isOpen?: boolean;\n header?: FC;\n hasCloseButton?: boolean;\n noBackdrop?: boolean;\n children: any;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onEnter?: () => void;\n};\n\nconst Modal: FC = (props) => {\n const {\n title,\n className,\n isOpen,\n header,\n hasCloseButton,\n noBackdrop,\n children,\n onClose,\n onCloseAnimationEnd,\n onEnter,\n } = props;\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n // eslint-disable-next-line no-null/no-null\n const modalRef = useRef(null);\n\n useEffect(() => (isOpen\n ? captureKeyboardListeners({ onEsc: onClose, onEnter })\n : undefined), [isOpen, onClose, onEnter]);\n useEffect(() => (isOpen && modalRef.current ? trapFocus(modalRef.current) : undefined), [isOpen]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n document.body.classList.toggle('has-open-dialog', isOpen);\n\n if (isOpen || (!isOpen && prevIsOpen !== undefined)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n\n return () => {\n document.body.classList.remove('has-open-dialog');\n };\n }, [isOpen]);\n\n const lang = useLang();\n\n if (!shouldRender) {\n return undefined;\n }\n\n function renderHeader() {\n if (header) {\n return header;\n }\n\n if (!title) {\n return undefined;\n }\n\n return (\n
\n {hasCloseButton && (\n \n \n \n )}\n
{title}
\n
\n );\n }\n\n const fullClassName = buildClassName(\n 'Modal',\n className,\n transitionClassNames,\n noBackdrop && 'transparent-backdrop',\n );\n\n return (\n \n \n
\n
\n
\n {renderHeader()}\n
\n {children}\n
\n
\n
\n
\n
\n );\n};\n\nexport default Modal;\n","export default function trapFocus(element: HTMLElement) {\n function handleKeyDown(e: KeyboardEvent) {\n if (e.key !== 'Tab') {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n const focusableElements = Array.from(\n element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'),\n ) as HTMLElement[];\n if (!focusableElements.length) {\n return;\n }\n\n const currentFocusedIndex = focusableElements.findIndex((em) => em.isSameNode(document.activeElement));\n let newFocusedIndex = 0;\n if (currentFocusedIndex >= 0) {\n if (e.shiftKey) {\n newFocusedIndex = currentFocusedIndex > 0\n ? currentFocusedIndex - 1\n : focusableElements.length - 1;\n } else {\n newFocusedIndex = currentFocusedIndex < focusableElements.length - 1\n ? currentFocusedIndex + 1\n : 0;\n }\n }\n\n focusableElements[newFocusedIndex].focus();\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/6.6418278736080b7f34a0.js b/dist/6.cd49d480ea2dfe303e7a.js similarity index 96% rename from dist/6.6418278736080b7f34a0.js rename to dist/6.cd49d480ea2dfe303e7a.js index 2ff51643..827703ff 100644 --- a/dist/6.6418278736080b7f34a0.js +++ b/dist/6.cd49d480ea2dfe303e7a.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[6],{133:function(t,e,i){"use strict";function s(t,e){return e-Math.floor(e/t)*t}i.d(e,"a",(function(){return s}))},181:function(t,e,i){"use strict";i.r(e);var s=i(298),n=i.n(s),r=i(7),a=i(22);function h(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class o{constructor(t){this.worker=t,h(this,"requestStates",new Map),h(this,"requestStatesByCallback",new Map),this.subscribe()}request(t){const{worker:e,requestStates:i,requestStatesByCallback:s}=this,n=Object(a.a)(i),r={type:"callMethod",messageId:n,...t},h={messageId:n},o=new Promise((t,e)=>{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(55),c=i(133);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.f?.75:1,l=.75,p=r.i?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(55),c=i(134);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.f?.75:1,l=.75,p=r.i?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"e24a786fd738bc16a030.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///./src/util/cycleRestrict.ts","webpack:///./src/util/WorkerConnector.ts","webpack:///./src/lib/rlottie/RLottie.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["cycleRestrict","length","index","Math","floor","WorkerConnector","constructor","worker","Map","this","subscribe","request","messageData","requestStates","requestStatesByCallback","messageId","generateIdFor","payload","type","requestState","promise","Promise","resolve","reject","Object","assign","args","callback","pop","set","catch","finally","delete","postMessage","cancelCallback","progressCallback","isCanceled","get","addEventListener","data","error","response","callbackArgs","HIGH_PRIORITY_QUALITY","IS_MOBILE_SCREEN","LOW_PRIORITY_QUALITY","HIGH_PRIORITY_CACHE_MODULO","IS_SAFARI","workers","Array","fill","undefined","map","Worker","lastWorkerIndex","RLottie","id","container","animationData","params","onLoad","document","createElement","canvas","getContext","initContainer","initConfig","initRenderer","isPlaying","isAnimating","isWaiting","play","stopFrameIndex","direction","doPlay","pause","approxFrameIndex","currentChunkIndex","getChunkIndex","chunks","chunk","i","goToAndPlay","frameIndex","reduceFactor","goToAndStop","playSegment","startFrameIndex","setSpeed","speed","destroy","isDestroyed","destroyRenderer","destroyContainer","parentNode","HTMLElement","Error","size","offsetWidth","parseInt","style","width","height","isLowPriority","quality","imgSize","round","max","DPR","appendChild","key","maxFps","sourceFps","fr","msPerFrame","cacheModulo","chunkSize","remove","workerIndex","name","onRendererInit","bind","framesCount","chunksCount","ceil","lastRenderAt","animate","isOnLoadFired","chunkIndex","requestChunk","cleanupPrevChunk","requestNextChunk","prevFrameIndex","frame","getFrame","imageData","ImageData","Uint8ClampedArray","ctx","putImageData","now","Date","currentSpeed","delta","min","expectedNextFrameIndex","noLoop","nextFrameIndex","indexInChunk","getFrameIndexInChunk","fromIndex","toIndex","onFrameLoad","prevChunkIndex","nextChunkIndex","arrayBuffer","module","exports"],"mappings":"0FAAe,SAASA,EAAcC,EAAgBC,GACpD,OAAOA,EAAQC,KAAKC,MAAMF,EAAQD,GAAUA,EAD9C,mC,qMCqDe,MAAMI,EAKnBC,YAAoBC,GAAgB,KAAhBA,SAAgB,uBAJZ,IAAIC,KAIQ,iCAFF,IAAIA,KAGpCC,KAAKC,YAGPC,QAAQC,GACN,MAAM,OAAEL,EAAF,cAAUM,EAAV,wBAAyBC,GAA4BL,KAErDM,EAAYC,YAAcH,GAC1BI,EAA0B,CAC9BC,KAAM,aACNH,eACGH,GAGCO,EAAe,CAAEJ,aAGjBK,EAAwB,IAAIC,QAA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PC,qBAAqBlE,GAE3B,OAAOA,EADY1E,KAAKqE,cAAcK,GACL1E,KAAK2G,UAGhCtC,cAAcK,GACpB,OAAOhF,KAAKC,MAAM+E,EAAa1E,KAAK2G,WAG9Ba,aAAaD,GACnB,GAAIvH,KAAKsE,OAAOiD,GACd,OAGFvH,KAAKsE,OAAOiD,GAAc,GAE1B,MAAMsB,EAAYtB,EAAavH,KAAK2G,UAC9BmC,EAAUpJ,KAAK6I,IAAIM,EAAY7I,KAAK2G,UAAY,EAAG3G,KAAKiH,YAAe,GAE7E1E,EAAQvC,KAAK6G,aAAa3G,QAAQ,CAChC4G,KAAM,eACN7F,KAAM,CAACjB,KAAKqG,IAAKwC,EAAWC,EAAS9I,KAAK+I,YAAY/B,KAAKhH,SAIvDyH,iBAAiBF,GACvB,GAAIvH,KAAKkH,YAAe,EACtB,OAGF,MAAM8B,EAAiBzJ,YAAcS,KAAKkH,YAAcK,EAAa,GACrEvH,KAAKsE,OAAO0E,QAAkBtG,EAGxBgF,iBAAiBH,GACvB,GAAyB,IAArBvH,KAAKkH,YACP,OAGF,MAAM+B,EAAiB1J,YAAcS,KAAKkH,YAAcK,EAAa,GAEhEvH,KAAKsE,OAAO2E,IACfjJ,KAAKwH,aAAayB,GAIdF,YAAYrE,EAAoBwE,GACtC,MAAM3B,EAAavH,KAAKqE,cAAcK,GAChCH,EAAQvE,KAAKsE,OAAOiD,GAErBhD,IAILA,EAAMvE,KAAK4I,qBAAqBlE,IAAewE,EAE3ClJ,KAAK6D,WACP7D,KAAKiE,a,oBCtaXkF,EAAOC,QAAU,WACf,OAAO,IAAIxG,OAAO,IAA0B","file":"6.cd49d480ea2dfe303e7a.js","sourcesContent":["export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import generateIdFor from './generateIdFor';\n\nexport interface CancellableCallback {\n (\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\ntype CallMethodData = {\n type: 'callMethod';\n messageId?: string;\n name: string;\n args: any;\n};\n\ntype OriginMessageData = CallMethodData | {\n type: 'cancelProgress';\n messageId: string;\n};\n\nexport interface OriginMessageEvent {\n data: OriginMessageData;\n}\n\nexport type WorkerMessageData = {\n type: 'methodResponse';\n messageId: string;\n response?: any;\n error?: { message: string };\n} | {\n type: 'methodCallback';\n messageId: string;\n callbackArgs: any[];\n} | {\n type: 'unhandledError';\n error?: { message: string };\n};\n\nexport interface WorkerMessageEvent {\n data: WorkerMessageData;\n}\n\ninterface RequestStates {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback: AnyToVoidFunction;\n}\n\n// TODO Replace `any` with proper generics\nexport default class WorkerConnector {\n private requestStates = new Map();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"b3cc7c4076a3189a6f9a.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/app-inactive.96b2f485d4875a6b65899d8ae2825b97.png b/dist/app-inactive.96b2f485d4875a6b65899d8ae2825b97.png deleted file mode 100644 index f2878d7f..00000000 Binary files a/dist/app-inactive.96b2f485d4875a6b65899d8ae2825b97.png and /dev/null differ diff --git a/dist/app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png b/dist/app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png new file mode 100644 index 00000000..fb0cd5f6 Binary files /dev/null and b/dist/app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png differ diff --git a/dist/e24a786fd738bc16a030.worker.js b/dist/b3cc7c4076a3189a6f9a.worker.js similarity index 98% rename from dist/e24a786fd738bc16a030.worker.js rename to dist/b3cc7c4076a3189a6f9a.worker.js index aafe2e2c..936b1d09 100644 --- a/dist/e24a786fd738bc16a030.worker.js +++ b/dist/b3cc7c4076a3189a6f9a.worker.js @@ -1,2 +1,2 @@ !function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";t.r(r);new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight;self.onerror=e=>{console.error(e),o({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),o({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const n=new Map;function o(e,r){r?postMessage(e,r):postMessage(e)}let s;self.importScripts("rlottie-wasm.js");const a=new Promise(e=>{Module.onRuntimeInitialized=()=>{s={init:Module.cwrap("lottie_init","",[]),destroy:Module.cwrap("lottie_destroy","",["number"]),resize:Module.cwrap("lottie_resize","",["number","number","number"]),buffer:Module.cwrap("lottie_buffer","number",["number"]),render:Module.cwrap("lottie_render","",["number","number"]),loadFromData:Module.cwrap("lottie_load_from_data","number",["number","number"])},e()}}),i=new Map;var c;c={init:async function(e,r,t,n,o,c){s||await a;const u=JSON.stringify(r),d=allocate(intArrayFromString(u),"i8",0),l=s.init(),f=s.loadFromData(l,d);s.resize(l,t,t),i.set(e,{imgSize:t,reduceFactor:o,handle:l}),c(Math.ceil(f/o))},renderFrames:async function(e,r,t,n){s||await a;const{imgSize:o,reduceFactor:c,handle:u}=i.get(e);for(let e=r;e<=t;e++){const r=e*c;s.render(u,r);const t=s.buffer(u),a=Module.HEAPU8.subarray(t,t+o*o*4);n(e,new Uint8ClampedArray(a).buffer)}},destroy:function(e){const r=i.get(e);s.destroy(r.handle),i.delete(e)}},onmessage=async e=>{const{data:r}=e;switch(r.type){case"callMethod":{const{messageId:e,name:t,args:s}=r;try{if(e){const r=(...r)=>{const t=r[r.length-1];o({type:"methodCallback",messageId:e,callbackArgs:r},t instanceof ArrayBuffer?[t]:void 0)};n.set(e,r),s.push(r)}const[r,a]=await c[t](...s)||[];e&&o({type:"methodResponse",messageId:e,response:r},a)}catch(r){e&&o({type:"methodResponse",messageId:e,error:{message:r.message}})}e&&n.delete(e);break}case"cancelProgress":{const e=n.get(r.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=e24a786fd738bc16a030.worker.js.map \ No newline at end of file +//# sourceMappingURL=b3cc7c4076a3189a6f9a.worker.js.map \ No newline at end of file diff --git a/dist/e24a786fd738bc16a030.worker.js.map b/dist/b3cc7c4076a3189a6f9a.worker.js.map similarity index 99% rename from dist/e24a786fd738bc16a030.worker.js.map rename to dist/b3cc7c4076a3189a6f9a.worker.js.map index 56f06bbb..8c425029 100644 --- a/dist/e24a786fd738bc16a030.worker.js.map +++ b/dist/b3cc7c4076a3189a6f9a.worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAo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ACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"e24a786fd738bc16a030.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC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AAUnD,IAAIU,GAE/B2B,EAAWS,QAAQiC,EAASd,QAE5Bd,EAAU6B,OAAOtE,KDzEjBuE,UAAY5B,UACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEsD,EAAF,KAAaxF,EAAb,KAAmByF,GAASjD,EAClC,IACE,GAAIgD,EAAW,CACb,MAAME,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnD5D,EAAa,CACXC,KAAM,iBACNsD,YACAG,gBACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlDzD,EAAcmC,IAAIe,EAAWE,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAUxD,SAAuBiB,EAAI1D,MAASyF,IAAU,GAE3DD,GACFvD,EACE,CACEC,KAAM,iBACNsD,YACAS,YAEFxD,GAGJ,MAAOT,GAMHwD,GACFvD,EAAa,CACXC,KAAM,iBACNsD,YACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"b3cc7c4076a3189a6f9a.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/0cfac43ee01937a2bf09.worker.js b/dist/e1066b23c5448d0199e4.worker.js similarity index 99% rename from dist/0cfac43ee01937a2bf09.worker.js rename to dist/e1066b23c5448d0199e4.worker.js index da58b70b..7e88f544 100644 --- a/dist/0cfac43ee01937a2bf09.worker.js +++ b/dist/e1066b23c5448d0199e4.worker.js @@ -1,3 +1,3 @@ -/*! For license information please see 0cfac43ee01937a2bf09.worker.js.LICENSE.txt */ +/*! For license information please see e1066b23c5448d0199e4.worker.js.LICENSE.txt */ !function(e){var t={};function n(s){if(t[s])return t[s].exports;var i=t[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(s,i,function(t){return e[t]}.bind(null,i));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=109)}([function(e,t,n){const s=n(6),i=n(81),a=n(40),r=n(20),o=n(98),c=n(99),u=n(21),l=n(27),d=n(103),f=n(33),g=n(8);e.exports={Api:s,TelegramClient:i,sessions:d,connection:a,extensions:f,tl:r,version:o,events:c,utils:u,errors:l,helpers:g}},function(e,t,n){"use strict";n.d(t,"f",(function(){return C})),n.d(t,"a",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"e",(function(){return E})),n.d(t,"g",(function(){return O})),n.d(t,"c",(function(){return U})),n.d(t,"i",(function(){return T})),n.d(t,"h",(function(){return B})),n.d(t,"d",(function(){return D}));var s={};n.r(s),n.d(s,"Type",(function(){return m})),n.d(s,"fetch",(function(){return y})),n.d(s,"save",(function(){return b})),n.d(s,"clear",(function(){return _}));var i=n(0),a=n(33),r=n(4),o=n(17),c=n(26),u=n(9),l=n(43),d=n(11),f=n(5),g=n(2),p=n(35);const h=self.caches;let m;async function y(e,t,n){if(h)try{const s=new Request(t),i=await h.open(e),a=await i.match(s);if(!a)return;switch(n){case m.Text:return await a.text();case m.Blob:{const e=await a.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=a.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case m.Json:return await a.json();default:return}}catch(e){return void console.warn(e)}}async function b(e,t,n){if(h)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),i=new Request(t),a=new Response(s),r=await h.open(e);return await r.put(i,a)}catch(e){return void console.warn(e)}}async function _(e){try{if(!h)return;return await h.delete(e)}catch(e){return void console.warn(e)}}async function w({url:e,mediaFormat:t,start:n,end:a},o,c,u){const{data:h,mimeType:m,fullSize:y}=await async function(e,t,n,s,a,o,c){const u=e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!u)return;if("file"===u[1]){const e=await fetch(u[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let l,p=u[2];const h=u[3]?u[3].replace("?size=",""):void 0;let m;"avatar"===u[1]||"profile"===u[1]?(l=Object(g.s)(Number(p)),p=Math.abs(Number(p))):l=u[1];switch(l){case"channel":case"chat":m=f.a.chats[p];break;case"user":m=f.a.users[p];break;case"msg":m=f.a.messages[p];break;case"sticker":case"gif":case"wallpaper":m=f.a.documents[p];break;case"photo":m=f.a.photos[p];break;case"stickerSet":m=f.a.stickerSets[p]}if(!m)return;if(["msg","sticker","gif","wallpaper","photo"].includes(l)){c===d.ApiMediaFormat.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(m,{sizeType:h,start:a,end:o,progressCallback:s,workers:r.j});let n,u;return m instanceof i.Api.Message?(n=function(e,t){if(!e||!e.media)return;if(e.media instanceof i.Api.MessageMediaPhoto)return"image/jpeg";if(e.media instanceof i.Api.MessageMediaDocument&&e.media.document instanceof i.Api.Document)return t?e.media.document.attributes.some(e=>e instanceof i.Api.DocumentAttributeSticker)?"image/webp":"image/jpeg":e.media.document.mimeType;return}(m,h),m.media instanceof i.Api.MessageMediaDocument&&m.media.document instanceof i.Api.Document&&(u=m.media.document.size)):m instanceof i.Api.Photo?n="image/jpeg":"sticker"===l&&h?n="image/webp":(n=m.mimeType,u=m.size),{mimeType:n,data:e,fullSize:u}}if("stickerSet"===l){const e=await t.downloadStickerSetThumb(m);return{mimeType:c===d.ApiMediaFormat.Lottie?"application/json":"image/jpeg",data:e}}{const e=await t.downloadProfilePhoto(m,"profile"===u[1]);return{mimeType:"image/jpeg",data:e}}}(e,o,c,u,n,a,t)||{};if(!h)return;const _=await async function(e,t,n){switch(t){case d.ApiMediaFormat.DataUri:return Object(p.a)(new Blob([e],{type:n}));case d.ApiMediaFormat.BlobUrl:return new Blob([e],{type:n});case d.ApiMediaFormat.Lottie:{const t=Object(l.inflate)(e,{to:"string"});return JSON.parse(t)}case d.ApiMediaFormat.Progressive:return e.buffer}return}(h,t,m);if(!_)return;const w=t!==d.ApiMediaFormat.Progressive&&(t!==d.ApiMediaFormat.BlobUrl||_.size<=r.n);if(!r.m&&s&&w){b(e.startsWith("avatar")?r.p:r.o,e,_)}return{prepared:t===d.ApiMediaFormat.Progressive?"":function(e){if(e instanceof Blob)return URL.createObjectURL(e);return e}(_),arrayBuffer:t===d.ApiMediaFormat.Progressive?_:void 0,mimeType:m,fullSize:y}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(m||(m={}));var v=n(13);a.Logger.setLevel(r.g?"debug":"warn");const A={build:e=>e};let I,P,S=!1;async function C(e,t){I=t,r.f&&console.log(">>> START INIT API");const n=r.k?new i.sessions.LocalStorageSession(e):new i.sessions.IdbSession(e);P=new i.TelegramClient(n,"739222","60d1e1063c72d4bc4cfdda99e8906f94",{useWSS:!0,additionalDcsDisabled:r.k}),P.addEventHandler(R,A),P.addEventHandler(c.b,A);try{r.f&&console.log("[GramJs/client] CONNECTING"),await P.start({phoneNumber:o.g,phoneCode:o.e,password:o.f,firstAndLastNames:o.i,qrCode:o.h,onError:o.b});const e=await n.save();r.f&&(console.log(">>> FINISH INIT API"),console.log("[GramJs/client] CONNECTED as ",e)),Object(o.c)(e),I({"@type":"updateApiReady"}),D()}catch(e){throw r.f&&console.log("[GramJs/client] CONNECTING ERROR",e),e}}async function M(){await O(new i.Api.auth.LogOut),await P.destroy()}async function k(){await P.disconnect()}function E(){return P}function R(e){e instanceof i.connection.UpdateConnectionState?S=e.state===i.connection.UpdateConnectionState.connected:e instanceof i.Api.UpdatesTooLong&&async function(){try{await O(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&I({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}()}async function O(e,t=!1,n=!1){if(S)try{r.f&&console.log("[GramJs/client] INVOKE "+e.className);const n=await P.invoke(e);if(r.f&&console.log("[GramJs/client] INVOKE RESPONSE "+e.className,n),t){let t;n instanceof i.Api.Updates||n instanceof i.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof i.Api.Updates||n.updates instanceof i.Api.UpdatesCombined)&&(t=n.updates),t?(!function(e){const t=[...e.users,...e.chats];e.updates.forEach(e=>{t&&(e._entities=t)})}(t),t.updates.forEach(t=>{Object(c.b)(t,e)})):n instanceof i.Api.UpdatesTooLong||Object(c.b)(n,e)}return n}catch(t){if(r.f&&(console.log("[GramJs/client] INVOKE ERROR "+e.className),console.error(t)),function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof i.Api.messages.SendMessage||t instanceof i.Api.messages.SendMedia||t instanceof i.Api.messages.SendMultiMedia),{message:s}=e;I({"@type":"error",error:{message:s,isSlowMode:n}})}(t,e),n)throw t;return}else r.f&&console.warn(`[GramJs/client] INVOKE ${e.className} ERROR: Client is not connected`)}function U(e,t){return w(e,P,S,t)}function T(e,t){return P.uploadFile({file:e,onProgress:t,workers:r.v})}function B(e){return P.updateTwoFaSettings(e)}async function D(){const e=await O(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}));if(!(e&&e.user instanceof i.Api.User))return;f.a.users[e.user.id]=e.user;const t=Object(v.b)(e);Object(u.o)(t.id),Object(o.d)(t)}},function(e,t,n){"use strict";(function(e){n.d(t,"s",(function(){return l})),n.d(t,"o",(function(){return d})),n.d(t,"i",(function(){return f})),n.d(t,"g",(function(){return p})),n.d(t,"l",(function(){return h})),n.d(t,"f",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"j",(function(){return b})),n.d(t,"d",(function(){return _})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return v})),n.d(t,"n",(function(){return A})),n.d(t,"q",(function(){return I})),n.d(t,"t",(function(){return P})),n.d(t,"u",(function(){return S})),n.d(t,"c",(function(){return C})),n.d(t,"e",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"a",(function(){return E})),n.d(t,"p",(function(){return R})),n.d(t,"k",(function(){return O}));var s=n(15),i=n.n(s),a=n(0),r=n(8),o=n(11),c=n(5),u=n(14);function l(e){return e>0?"user":e<=-1e9?"channel":"chat"}function d(e){return e>0?new a.Api.PeerUser({userId:e}):e<=-1e9?new a.Api.PeerChannel({channelId:-e}):new a.Api.PeerChat({chatId:-e})}function f(e,t){return e>0||e<=-1e9?e>0?new a.Api.InputPeerUser({userId:e,accessHash:i()(t)}):new a.Api.InputPeerChannel({channelId:-e,accessHash:i()(t)}):new a.Api.InputPeerChat({chatId:-e})}function g(e){if(e>0){const{accessHash:t}=c.a.users[e]||{};return t?new a.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=c.a.chats[-e]||{};return t?new a.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new a.Api.InputPeerChat({chatId:-e})}function p(e,t){return e>0?new a.Api.InputUser({userId:e,accessHash:i()(t)}):e<=-1e9?new a.Api.InputChannel({channelId:-e,accessHash:i()(t)}):-e}function h(e,t){return new a.Api.InputStickerSetID({id:i()(e),accessHash:i()(t)})}function m(e){const t=c.a.documents[e.id];if(t)return new a.Api.InputDocument(Object(u.b)(t,["id","accessHash","fileReference"]))}function y(e){const t=m(e);if(t)return new a.Api.InputMediaDocument({id:t})}function b(t,n){const{summary:s,quiz:i}=t,r=new a.Api.Poll({id:n,publicVoters:s.isPublic,question:s.question,answers:s.answers.map(({text:t,option:n})=>new a.Api.PollAnswer({text:t,option:e.from(n)})),quiz:s.quiz,multipleChoice:s.multipleChoice});if(!i)return new a.Api.InputMediaPoll({poll:r});const o=i.correctAnswers.map(t=>e.from(t)),{solution:c}=i,u=i.solutionEntities?i.solutionEntities.map(A):[];return new a.Api.InputMediaPoll({poll:r,correctAnswers:o,...c&&{solution:c,solutionEntities:u}})}function _(e){const{emoticon:t,contacts:n,nonContacts:s,groups:i,channels:r,bots:o,excludeArchived:c,excludeMuted:u,excludeRead:l,pinnedChatIds:d,includedChatIds:f,excludedChatIds:p}=e,h=d?d.map(g).filter(Boolean):[],m=f?f.map(g).filter(Boolean):[],y=p?p.map(g).filter(Boolean):[];return new a.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:i||void 0,bots:o||void 0,excludeArchived:c||void 0,excludeMuted:u||void 0,excludeRead:l||void 0,broadcasts:r||void 0,pinnedPeers:h,includePeers:m,excludePeers:y})}function w(){return Object(r.readBigIntFromBuffer)(Object(r.generateRandomBytes)(8),!0,!0)}function v(e,t,n){return new a.Api.Message({id:e,peerId:d(t),fromId:d(t),media:n.media})}function A(e){const{type:t,offset:n,length:s,url:i,userId:r}=e,u=r?c.a.users[r]:void 0;switch(t){case o.ApiMessageEntityTypes.Bold:return new a.Api.MessageEntityBold({offset:n,length:s});case o.ApiMessageEntityTypes.Italic:return new a.Api.MessageEntityItalic({offset:n,length:s});case o.ApiMessageEntityTypes.Underline:return new a.Api.MessageEntityUnderline({offset:n,length:s});case o.ApiMessageEntityTypes.Strike:return new a.Api.MessageEntityStrike({offset:n,length:s});case o.ApiMessageEntityTypes.Code:return new a.Api.MessageEntityCode({offset:n,length:s});case o.ApiMessageEntityTypes.Pre:return new a.Api.MessageEntityPre({offset:n,length:s,language:""});case o.ApiMessageEntityTypes.Blockquote:return new a.Api.MessageEntityBlockquote({offset:n,length:s});case o.ApiMessageEntityTypes.TextUrl:return new a.Api.MessageEntityTextUrl({offset:n,length:s,url:i});case o.ApiMessageEntityTypes.Url:return new a.Api.MessageEntityUrl({offset:n,length:s});case o.ApiMessageEntityTypes.Hashtag:return new a.Api.MessageEntityHashtag({offset:n,length:s});case o.ApiMessageEntityTypes.MentionName:return new a.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new a.Api.InputUser({userId:r,accessHash:u.accessHash})});default:return new a.Api.MessageEntityUnknown({offset:n,length:s})}}function I(e){let t=0;return e.forEach(e=>{t=(20261*t&2147483647)+e&2147483647}),t}function P(e){const{media:t}=e;return!!t&&(t instanceof a.Api.MessageMediaPhoto||t instanceof a.Api.MessageMediaDocument||t instanceof a.Api.MessageMediaWebPage&&t.webpage instanceof a.Api.WebPage&&t.webpage.photo instanceof a.Api.Photo)}function S(e){return"photo"in e.action&&e.action.photo instanceof a.Api.Photo}function C(e){if(e instanceof a.Api.PhotoEmpty)return new a.Api.ChatPhotoEmpty;const{dcId:t}=e,n=e.sizes.filter(e=>e instanceof a.Api.PhotoSize||e instanceof a.Api.PhotoCachedSize);if(!n.length)return new a.Api.ChatPhotoEmpty;const s=n.find(e=>"a"===e.type),i=n.find(e=>"c"===e.type)||n.find(e=>"b"===e.type);return s&&i?new a.Api.ChatPhoto({dcId:t,photoSmall:s&&s.location,photoBig:i&&i.location}):new a.Api.ChatPhotoEmpty}function M({phone:e,firstName:t,lastName:n}){return new a.Api.InputPhoneContact({clientId:i()(1),phone:e,firstName:t,lastName:n})}function k(e,t=0){return new a.Api.ChatBannedRights({...e,untilDate:t})}function E(e){return new a.Api.ChatAdminRights(e)}function R(e){const{shippingAddress:t}=e;return new a.Api.PaymentRequestedInfo({...e,shippingAddress:t?new a.Api.PostAddress(t):void 0})}function O(e){switch(e){case"phoneNumber":return new a.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new a.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new a.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new a.Api.InputPrivacyKeyForwards;case"chatInvite":return new a.Api.InputPrivacyKeyChatInvite}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return p})),n.d(t,"k",(function(){return h})),n.d(t,"j",(function(){return m})),n.d(t,"l",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"g",(function(){return A})),n.d(t,"h",(function(){return I})),n.d(t,"f",(function(){return P})),n.d(t,"i",(function(){return S})),n.d(t,"a",(function(){return C})),n.d(t,"b",(function(){return M}));var s=n(0),i=n(14);function a(e){return e.hasOwnProperty("userId")}function r(e){return e.hasOwnProperty("chatId")}var o=n(18);function c(e,t=!1){const n=Boolean("min"in e&&e.min),i="accessHash"in e&&String(e.accessHash),a="photo"in e&&v(e.photo),r=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:r,...i&&{accessHash:i},...a&&{avatarHash:a},...(e instanceof s.Api.Channel||e instanceof s.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},...(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...l(e),..."creator"in e&&{isCreator:e.creator},...d(e),...f(e)}}function u(e,t){const{peer:n,folderId:s,unreadMark:i,unreadCount:a,unreadMentionsCount:r,notifySettings:{silent:o,muteUntil:u},readOutboxMaxId:l,readInboxMaxId:d}=e,f=o||"number"==typeof u&&Date.now()<1e3*u;return{id:h(n),...s&&{folderId:s},type:y(t),title:_(n,t),lastReadOutboxMessageId:l,lastReadInboxMessageId:d,unreadCount:a,unreadMentionsCount:r,isMuted:f,...i&&{hasUnreadMark:!0},...c(t)}}function l(e){return e instanceof s.Api.Chat||e instanceof s.Api.Channel?{adminRights:Object(o.b)(e.adminRights),currentUserBannedRights:e instanceof s.Api.Channel?Object(o.b)(e.bannedRights):void 0,defaultBannedRights:Object(o.b)(e.defaultBannedRights)}:{}}function d(e){if(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden)return{isRestricted:!0};if(e instanceof s.Api.User)return{isRestricted:e.restricted,restrictionReason:g(e.restrictionReason)};if(e instanceof s.Api.Chat)return{isNotJoined:e.left,isRestricted:e.kicked};if(e instanceof s.Api.Channel){const t=e.restricted&&e.restrictionReason&&e.restrictionReason.some(e=>"all"===e.platform);return{isNotJoined:e.left,isRestricted:t,restrictionReason:g(e.restrictionReason)}}return{}}function f(e){return e instanceof s.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof s.Api.InputChannelEmpty)?{migratedTo:{chatId:h(e.migratedTo),...e.migratedTo instanceof s.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function g(e){if(!e)return;const t=e.find(({platform:e})=>"all"===e);return t?Object(i.b)(t,["reason","text"]):void 0}function p(e,t=!1,n=!1){if(e instanceof s.Api.Chat||e instanceof s.Api.Channel||e instanceof s.Api.User||n&&(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden))return{id:e instanceof s.Api.User?e.id:-e.id,type:y(e),title:e instanceof s.Api.User?w(e):e.title,...c(e,t)}}function h(e){return a(e)?e.userId:r(e)?-e.chatId:-e.channelId}function m(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function y(e){return e instanceof s.Api.User||e instanceof s.Api.UserEmpty?"chatTypePrivate":e instanceof s.Api.Chat||e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function b(e){return a(e)?"user"+e.userId:r(e)?"chat"+e.chatId:"chat"+e.channelId}function _(e,t){return a(e)?w(t):t.title}function w(e){return e.firstName?`${e.firstName}${e.lastName?" "+e.lastName:""}`:e.lastName||void 0}function v(e){if(e instanceof s.Api.UserProfilePhoto)return e.photoId.toString();if(e instanceof s.Api.ChatPhoto){const{dcId:t,photoSmall:{volumeId:n,localId:s}}=e;return`${t}-${n}-${s}`}}function A(e){return{userId:e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?Object(o.b)(e.bannedRights):void 0,adminRights:"adminRights"in e?Object(o.b)(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof s.Api.ChannelParticipantAdmin||e instanceof s.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof s.Api.ChannelParticipantCreator||e instanceof s.Api.ChatParticipantCreator)&&{isOwner:!0}}}function I(e){return e instanceof s.Api.ChatParticipants||e instanceof s.Api.channels.ChannelParticipants?e.participants.map(A):void 0}function P(e){return e instanceof s.Api.ChatInviteExported?e.link:void 0}function S(e){let t="";if(!(e.action instanceof s.Api.SendMessageCancelAction))return e.action instanceof s.Api.SendMessageTypingAction?t="typing":e.action instanceof s.Api.SendMessageRecordVideoAction?t="recording a video":e.action instanceof s.Api.SendMessageUploadVideoAction?t="uploading a video":e.action instanceof s.Api.SendMessageRecordAudioAction?t="recording a voice message":e.action instanceof s.Api.SendMessageUploadAudioAction?t="uploading a voice message":e.action instanceof s.Api.SendMessageUploadPhotoAction?t="uploading a photo":e.action instanceof s.Api.SendMessageUploadDocumentAction?t="uploading a file":e.action instanceof s.Api.SendMessageGeoLocationAction?t="selecting a location to share":e.action instanceof s.Api.SendMessageChooseContactAction?t="selecting a contact to share":e.action instanceof s.Api.SendMessageGamePlayAction?t="playing a game":e.action instanceof s.Api.SendMessageRecordRoundAction?t="recording a round video":e.action instanceof s.Api.SendMessageUploadRoundAction&&(t="uploading a round video"),{action:t,...e instanceof s.Api.UpdateChatUserTyping&&{userId:e.userId},...e instanceof s.Api.UpdateChannelUserTyping&&{userId:e.userId},timestamp:Date.now()}}function C(e){return{...Object(i.c)(e,["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"]),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(m).filter(Boolean),includedChatIds:e.includePeers.map(m).filter(Boolean),excludedChatIds:e.excludePeers.map(m).filter(Boolean)}}function M({filter:e,description:t}){return{...C(e),description:t}}},function(e,t,n){"use strict";n.d(t,"f",(function(){return s})),n.d(t,"k",(function(){return i})),n.d(t,"g",(function(){return a})),n.d(t,"m",(function(){return r})),n.d(t,"o",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"n",(function(){return u})),n.d(t,"c",(function(){return l})),n.d(t,"b",(function(){return d})),n.d(t,"j",(function(){return f})),n.d(t,"v",(function(){return g})),n.d(t,"q",(function(){return p})),n.d(t,"s",(function(){return h})),n.d(t,"e",(function(){return m})),n.d(t,"t",(function(){return y})),n.d(t,"l",(function(){return b})),n.d(t,"r",(function(){return _})),n.d(t,"u",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"d",(function(){return A})),n.d(t,"i",(function(){return I})),n.d(t,"h",(function(){return P}));const s=!1,i=!1,a=!1,r=!1,o="tt-media",c="tt-media-avatars",u=524288,l=300,d=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),f=16,g=16,p=("undefined"!=typeof window&&window.innerHeight,200),h=50,m=100,y=40,b=1e9,_="MEMOJI_STICKER",w=777e3,v=0,A=1,I=777,P="android"},function(e,t,n){"use strict";t.a={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:a,serializeDate:r}=n(45),{readBufferFromBigInt:o,toSignedLittleBuffer:c}=n(8),u=n(79),l=n(80),d="undefined"!=typeof self&&void 0!==self.localStorage;function f(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 g(e,n){switch(n){case"int":const n=t.alloc(4);return n.writeInt32LE(e,0),n;case"long":return c(e,8);case"int128":return c(e,16);case"int256":return c(e,32);case"double":const s=t.alloc(8);return s.writeDoubleLE(e,0),s;case"string":return a(e);case"Bool":return e?t.from("b5757299","hex"):t.from("379779bc","hex");case"true":return t.alloc(0);case"bytes":return a(e);case"date":return r(e);default:return e.getBytes()}}function p(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let i=0;i{this[e]=t[e]})}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<g(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]||null===this[t]?e|=0:e|=1</);if(n){t.readInt();let 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}(h("constructor",e.constructors),h("request",e.requests))}()}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"p",(function(){return p})),n.d(t,"j",(function(){return h})),n.d(t,"k",(function(){return m})),n.d(t,"w",(function(){return y})),n.d(t,"h",(function(){return b})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"H",(function(){return A})),n.d(t,"b",(function(){return I})),n.d(t,"q",(function(){return P})),n.d(t,"r",(function(){return S})),n.d(t,"d",(function(){return C})),n.d(t,"c",(function(){return M})),n.d(t,"g",(function(){return k})),n.d(t,"z",(function(){return E})),n.d(t,"y",(function(){return R})),n.d(t,"i",(function(){return O})),n.d(t,"n",(function(){return U})),n.d(t,"f",(function(){return T})),n.d(t,"e",(function(){return B})),n.d(t,"A",(function(){return D})),n.d(t,"o",(function(){return x})),n.d(t,"B",(function(){return j})),n.d(t,"F",(function(){return N})),n.d(t,"G",(function(){return F})),n.d(t,"E",(function(){return V})),n.d(t,"I",(function(){return L})),n.d(t,"D",(function(){return q})),n.d(t,"C",(function(){return H})),n.d(t,"m",(function(){return z})),n.d(t,"l",(function(){return K})),n.d(t,"x",(function(){return G})),n.d(t,"s",(function(){return W})),n.d(t,"t",(function(){return J}));var s=n(0),i=n(4),a=n(1),r=n(3),o=n(9),c=n(13),u=n(14),l=n(5),d=n(2),f=n(16);let g;function p(e){g=e}async function h({limit:e,offsetDate:t,archived:n,withPinned:l}){const d=await Object(a.g)(new s.Api.messages.GetDialogs({offsetPeer:new s.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?i.d:void 0,...l&&{excludePinned:!0}})),f=l?await Object(a.g)(new s.Api.messages.GetPinnedDialogs({folderId:n?i.d:void 0})):void 0;if(!d||d instanceof s.Api.messages.DialogsNotModified)return;Z(d),f&&Z(f);const g=Object(u.a)([...d.messages,...f?f.messages:[]].map(o.b).filter(Boolean),"chatId"),p={...$(d),...f&&$(f)},h=[],m={},y={},b=[...f?f.dialogs:[],...d.dialogs],_=[];b.forEach(e=>{if(!(e instanceof s.Api.Dialog)||!n&&e.folderId===i.d||n&&e.folderId!==i.d)return;const t=p[Object(r.l)(e.peer)],a=Object(r.c)(e,t);if(a.lastMessage=g[a.id],h.push(a),l&&e.pinned&&_.push(a.id),e.draft){const{formattedText:t,replyingToId:n}=Object(o.h)(e.draft)||{};t&&(m[a.id]=t),n&&(y[a.id]=n)}});const w=[...d.users,...f?f.users:[]].map(c.a).filter(Boolean),v=h.map(e=>e.id);let A;return A=d instanceof s.Api.messages.DialogsSlice?d.count:v.length,{chatIds:v,chats:h,users:w,draftsById:m,replyingToById:y,orderedPinnedIds:l?_:void 0,totalChatCount:A}}function m(e){const{id:t,accessHash:n,adminRights:i}=e;return Object(d.g)(t,n)instanceof s.Api.InputChannel?async function(e,t,n){const i=await Object(a.g)(new s.Api.channels.GetFullChannel({channel:Object(d.g)(e,t)}));if(!(i&&i.fullChat instanceof s.Api.ChannelFull))return;const{about:o,onlineCount:c,exportedInvite:u,slowmodeSeconds:l,slowmodeNextSendDate:f,migratedFromChatId:g,migratedFromMaxId:p,canViewParticipants:h,linkedChatId:m,hiddenPrehistory:y}=i.fullChat,b=u instanceof s.Api.ChatInviteExported?u.link:void 0,{members:_,users:w}=h&&await z(e,t)||{},{members:v,users:A}=h&&n&&await z(e,t,"kicked")||{},{members:I,users:P}=h&&n&&await z(e,t,"admin")||{};return{fullInfo:{about:o,onlineCount:c,inviteLink:b,slowMode:l?{seconds:l,nextSendDate:f}:void 0,migratedFrom:g?{chatId:Object(r.k)({chatId:g}),maxMessageId:p}:void 0,canViewMembers:h,isPreHistoryHidden:y,members:_,kickedMembers:v,adminMembers:I,linkedChatId:m?Object(r.k)({chatId:m}):void 0},users:[...w||[],...A||[],...P||[]]}}(t,n,i):async function(e){const t=await Object(a.g)(new s.Api.messages.GetFullChat({chatId:Object(d.g)(e)}));if(!(t&&t.fullChat instanceof s.Api.ChatFull))return;Z(t);const{about:n,participants:i,exportedInvite:o}=t.fullChat,u=Object(r.h)(i),l=u?u.filter(({isAdmin:e,isOwner:t})=>e||t):void 0;return{fullInfo:{about:n,members:u,adminMembers:l,inviteLink:Object(r.f)(o),canViewMembers:!0},users:t.users.map(c.a).filter(Boolean)}}(t)}async function y({query:e}){const t=await Object(a.g)(new s.Api.contacts.Search({q:e}));if(!t)return;Z(t);const n=t.myResults.map(r.k),i=[...t.chats,...t.users].map(e=>Object(r.d)(e)).filter(Boolean),o=t.users.map(c.a).filter(e=>!!e&&!e.isSelf);return{localChats:i.filter(e=>n.includes(e.id)),localUsers:o.filter(e=>n.includes(e.id)),globalChats:i.filter(e=>!n.includes(e.id)),globalUsers:o.filter(e=>!n.includes(e.id))}}async function b({type:e,user:t}){let n;if("self"===e||"user"===e){const i=await Object(a.g)(new s.Api.users.GetUsers({id:["user"===e&&t?Object(d.g)(t.id,t.accessHash):new s.Api.InputUserSelf]}));if(!i||!i.length)return;[n]=i}else if("support"===e){const e=await Object(a.g)(new s.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const i=Object(r.d)(n,"support"===e);if(i)return g({"@type":"updateChat",id:i.id,chat:i}),{chatId:i.id}}async function _(e){const{id:t,accessHash:n}=e,i=await Object(a.g)(new s.Api.messages.GetPeerDialogs({peers:[new s.Api.InputDialogPeer({peer:Object(d.i)(t,n)})]}));if(!i)return;const c=i.dialogs[0];if(!(c&&c instanceof s.Api.Dialog))return;const u=$(i)[Object(r.l)(c.peer)];if(!u)return;Z(i);const l=Object(o.b)(i.messages[0]);g({"@type":"updateChat",id:t,chat:{...Object(r.c)(c,u),lastMessage:l}})}function w({chat:e,text:t,entities:n,replyToMsgId:i}){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(d.i)(e.id,e.accessHash),message:t,...n&&{entities:n.map(d.n)},replyToMsgId:i}))}function v(e){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(d.i)(e.id,e.accessHash),message:""}))}async function A({chat:e,isMuted:t}){await Object(a.g)(new s.Api.account.UpdateNotifySettings({peer:new s.Api.InputNotifyPeer({peer:Object(d.i)(e.id,e.accessHash)}),settings:new s.Api.InputPeerNotifySettings({muteUntil:t?2**31-1:void 0})})),_(e)}async function I({title:e,about:t,users:n}){const o=await Object(a.g)(new s.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(o instanceof s.Api.Updates))return void(i.f&&console.error("Unexpected channel creation update",o));const c=o.chats[0];if(!(c&&c instanceof s.Api.Channel))return void(i.f&&console.error("Created channel not found",o));const u=Object(r.d)(c);return await Object(a.g)(new s.Api.channels.InviteToChannel({channel:Object(d.g)(u.id,u.accessHash),users:n.map(({id:e,accessHash:t})=>Object(d.g)(e,t))})),u}function P({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.JoinChannel({channel:Object(d.g)(e,t)}),!0)}function S({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.LeaveChannel({channel:Object(d.g)(e,t)}),!0)}function C({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.DeleteChannel({channel:Object(d.g)(e,t)}),!0)}async function M({title:e,users:t}){const n=await Object(a.g)(new s.Api.messages.CreateChat({title:e,users:t.map(({id:e,accessHash:t})=>Object(d.g)(e,t))}),!0);if(!(n instanceof s.Api.Updates))return void(i.f&&console.error("Unexpected chat creation update",n));const o=n.chats[0];if(o&&o instanceof s.Api.Chat)return Object(r.d)(o);i.f&&console.error("Created chat not found",n)}async function k({chatId:e,accessHash:t,photo:n}){const i=await Object(a.i)(n),r=Object(d.g)(e,t);return Object(a.g)(r instanceof s.Api.InputChannel?new s.Api.channels.EditPhoto({channel:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}):new s.Api.messages.EditChatPhoto({chatId:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}),!0)}async function E({chat:e,shouldBePinned:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.ToggleDialogPin({peer:new s.Api.InputDialogPeer({peer:Object(d.i)(n,i)}),pinned:t||void 0}))&&g({"@type":"updateChatPinned",id:e.id,isPinned:t})}function R({chat:e,folderId:t}){const{id:n,accessHash:i}=e;return Object(a.g)(new s.Api.folders.EditPeerFolders({folderPeers:[new s.Api.InputFolderPeer({peer:Object(d.i)(n,i),folderId:t})]}),!0)}async function O(){const e=await Object(a.g)(new s.Api.messages.GetDialogFilters);if(e)return{byId:Object(u.a)(e.map(r.a),"id"),orderedIds:e.map(({id:e})=>e)}}async function U(){const e=await Object(a.g)(new s.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(r.b)}async function T({id:e,folderUpdate:t}){const n=Object(d.d)(t);await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&g({"@type":"updateChatFolder",id:e,folder:t})}async function B(e){const t=await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await U();t&&g({"@type":"updateChatFolder",id:e,folder:void 0}),n&&g({"@type":"updateRecommendedChatFolders",folders:n})}async function D({chat:e,hasUnreadMark:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.MarkDialogUnread({peer:new s.Api.InputDialogPeer({peer:Object(d.i)(n,i)}),unread:t||void 0}))&&g({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function x(e){const t=await Object(a.g)(new s.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:i}=t,o=i.length?Object(r.d)(i[0]):Object(r.d)(n[0]);return o?(Z(t),o):void 0}function j({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(d.g)(n,i);return Object(a.g)(new s.Api.channels.TogglePreHistoryHidden({channel:r,enabled:t}),!0)}function N({chat:e,bannedRights:t}){const{id:n,accessHash:i}=e,r=Object(d.i)(n,i);return Object(a.g)(new s.Api.messages.EditChatDefaultBannedRights({peer:r,bannedRights:Object(d.b)(t)}),!0)}function F({chat:e,user:t,bannedRights:n}){const i=Object(d.g)(e.id,e.accessHash),r=Object(d.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditBanned({channel:i,userId:r,bannedRights:Object(d.b)(n)}),!0)}function V({chat:e,user:t,adminRights:n,customTitle:i=""}){const r=Object(d.g)(e.id,e.accessHash),o=Object(d.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditAdmin({channel:r,userId:o,adminRights:Object(d.a)(n),rank:i}),!0)}async function L(e,t){const n=Object(d.g)(e.id,e.accessHash);await Object(a.g)(n instanceof s.Api.InputChannel?new s.Api.channels.EditTitle({channel:n,title:t}):new s.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function q(e,t){await Object(a.g)(new s.Api.messages.EditChatAbout({peer:Object(d.i)(e.id,e.accessHash),about:t}))&&g({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function H({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(d.g)(n,i);return Object(a.g)(new s.Api.channels.ToggleSignatures({channel:r,enabled:t}),!0)}async function z(e,t,n="recent",o){let u;switch(n){case"kicked":u=new s.Api.ChannelParticipantsKicked({q:""});break;case"admin":u=new s.Api.ChannelParticipantsAdmins;break;default:u=new s.Api.ChannelParticipantsRecent}const l=await Object(a.g)(new s.Api.channels.GetParticipants({channel:Object(d.g)(e,t),filter:u,offset:o,limit:i.q}));if(l&&!(l instanceof s.Api.channels.ChannelParticipantsNotModified))return Z(l),{members:Object(r.h)(l),users:l.users.map(c.a).filter(Boolean)}}async function K(){const e=await Object(a.g)(new s.Api.channels.GetGroupsForDiscussion);if(e)return Z(e),e.chats.map(e=>Object(r.d)(e))}function G({channel:e,chat:t}){return Object(a.g)(new s.Api.channels.SetDiscussionGroup({broadcast:Object(d.i)(e.id,e.accessHash),group:t?Object(d.i)(t.id,t.accessHash):new s.Api.InputChannelEmpty}))}async function W(e){const t=await Object(a.g)(new s.Api.messages.MigrateChat({chatId:Object(d.g)(e.id)}),!0);if(t&&t instanceof s.Api.Updates)return Z(t),Object(r.d)(t.chats[1]);i.f&&console.error("Unexpected channel creation update",t)}async function J(e){const t=await Object(a.g)(new s.Api.messages.CheckChatInvite({hash:e}));if(t)return t instanceof s.Api.ChatInvite?void await Object(a.g)(new s.Api.messages.ImportChatInvite({hash:e}),!0):Object(r.d)(t.chat)}function $(e){const t={};return e.chats.forEach(e=>{t["chat"+e.id]=e}),e.users.forEach(e=>{t["user"+e.id]=e}),t}function Z(e){"users"in e&&e.users.forEach(e=>{e instanceof s.Api.User&&(l.a.users[e.id]=e)}),"chats"in e&&e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(l.a.chats[e.id]=e)}),"messages"in e&&e.messages.forEach(e=>{e instanceof s.Api.Message&&Object(d.t)(e)&&Object(f.a)(e)})}},function(e,t,n){(function(t){const s=n(36),i=n(15);function a(e,n=!0,s=!1){let a=t.from(e);const r=a.length;n&&(a=a.reverse());let o=i(a.toString("hex"),16);return s&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(i(2).pow(i(8*r)))),o}function r(e,n=8){const s=i(e),a=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0},generateRandomBytes:c,generateKeyDataFromNonce:async function(e,n){e=r(e,16),n=r(n,32);const[s,i,a]=await Promise.all([u(t.concat([n,e])),u(t.concat([e,n])),u(t.concat([n,n]))]);return{key:t.concat([s,i.slice(0,12)]),iv:t.concat([i.slice(12,20),a,n.slice(0,4)])}},sha1:u,sha256:function(e){const t=s.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=i.one,a=e;for(;t.greater(i.zero);){const e=t.remainder(i(2));t=t.divide(i(2)),e.eq(i.one)&&(s=s.multiply(a),s=s.remainder(n)),a=a.multiply(a),a=a.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 o(i(e),s,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const n=t.alloc(4*e.length);for(let t=0;t1?"s":""})`}}else if(e instanceof s.Api.MessageActionContactSignUp)o="%action_origin% joined Telegram";else if(e instanceof s.Api.MessageActionPaymentSent){const t=d(e.currency),n=(Number(e.totalAmount)/100).toFixed(2);o=`You successfully transferred ${t}${n} to shop for %product%`}else o="%ACTION_NOT_IMPLEMENTED%";"photo"in e&&e.photo instanceof s.Api.Photo&&(Object(g.b)(e.photo),a=Object(c.a)(e.photo));return{text:o,type:u,targetUserId:l,targetChatId:f,photo:a}}(t.action,n,Boolean(t.post),a);u&&(o.action=u);const{replyToMsgId:l,replyToTopId:f}=t.replyTo||{},h=t.editDate&&!t.editHide,{inlineButtons:m,keyboardButtons:y}=function(e){const{id:t,replyMarkup:n,media:i}=e;if(!n)return i instanceof s.Api.MessageMediaWebPage&&i.webpage instanceof s.Api.WebPage&&"telegram_message"===i.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:i.webpage.url}]]}:void 0;if(!(n instanceof s.Api.ReplyKeyboardMarkup||n instanceof s.Api.ReplyInlineMarkup))return;const a=n.rows.map(({buttons:e})=>e.map(e=>{let n,a,{text:r}=e;return e instanceof s.Api.KeyboardButton?(n="command",a=r):e instanceof s.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof s.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof s.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof s.Api.KeyboardButtonBuy?(i instanceof s.Api.MessageMediaInvoice&&i.receiptMsgId&&(r="Receipt",a=i.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:r,messageId:t,value:a}}));return{[n instanceof s.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a}}(t)||{},b=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&Object(r.k)(e.savedFromPeer),s=e.fromId&&Object(r.k)(e.fromId);return{isChannelPost:Boolean(e.channelPost),isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,i),{replies:_,mediaUnread:w,postAuthor:v}=t,I=t.groupedId&&t.groupedId.toString(),S=Boolean(I)&&!(o.document||o.audio),C=t.replyMarkup instanceof s.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:a,content:o,date:t.date,senderId:n||t.out&&t.post&&p||e,views:t.views,isFromScheduled:t.fromScheduled,...l&&{replyToMessageId:l},...f&&{replyToTopMessageId:f},...b&&{forwardInfo:b},...h&&{isEdited:h},...w&&{isMediaUnread:w},...t.mentioned&&w&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:S},inlineButtons:m,...y&&{keyboardButtons:y},...C&&{shouldHideKeyboardButtons:C},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:D(_,t.id,e)},...v&&{adminTitle:v}}}function A(e,t){return{text:e,...t&&{entities:t.map(B)}}}function I(e){if(!(e instanceof s.Api.DraftMessageEmpty)&&e.message)return{formattedText:A(e.message,e.entities),replyingToId:e.replyToMsgId}}function P(e){const t=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;return Object(o.a)(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(!(e instanceof s.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof s.Api.Photo))return;if(e.ttlSeconds)return;return Object(c.a)(e.photo)}(e);if(n)return{photo:n};const i=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document instanceof s.Api.Document&&e.document.mimeType.startsWith("video")))return;return S(e.document)}(e);if(i)return{video:i};const r=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||t.voice)return;return{fileName:R(e.document,"audio"),...Object(a.b)(e.document,["size","mimeType"]),...Object(a.b)(t,["duration","performer","title"])}}(e);if(r)return{audio:r};const u=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||!t.voice)return;const{duration:n,waveform:i}=t;return{duration:n,waveform:i?Array.from(i):void 0}}(e);if(u)return{voice:u};const l=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document))return;if(e.ttlSeconds)return;return C(e.document)}(e);if(l)return{document:l};const f=function(e){if(!(e instanceof s.Api.MessageMediaContact))return;return Object(a.b)(e,["firstName","lastName","phoneNumber","userId"])}(e);if(f)return{contact:f};const g=function(e){if(!(e instanceof s.Api.MessageMediaPoll))return;return M(e.poll,e.results)}(e);if(g)return{poll:g};const p=E(e);if(p)return{webPage:p};const h=function(e){if(!(e instanceof s.Api.MessageMediaInvoice))return;return function(e){const{description:t,title:n,photo:s,test:i,totalAmount:a,currency:r,receiptMsgId:o}=e,c=d(r);return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,description:`${c}${(Number(a)/100).toFixed(2)} ${i?"TEST INVOICE":""}`}}(e)}(e);return h?{invoice:h}:void 0}function S(e){if(e instanceof s.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:i,size:a,attributes:r}=e,o=r.find(e=>e instanceof s.Api.DocumentAttributeVideo);if(!o)return;const u=r.find(e=>e instanceof s.Api.DocumentAttributeAnimated),{duration:l,w:d,h:f,supportsStreaming:g=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:l,fileName:R(e,"video"),width:d,height:f,supportsStreaming:g,isRound:p,isGif:Boolean(u),thumbnail:Object(c.e)(i),size:a}}function C(e){if(!(e instanceof s.Api.Document))return;const{id:t,size:n,mimeType:i,date:a,thumbs:r}=e,o=r&&Object(c.e)(r);return{id:String(t),size:n,mimeType:i,timestamp:a,fileName:R(e),thumbnail:o}}function M(e,t){const{id:n,answers:s}=e,i=s.map(e=>({text:e.text,option:String.fromCharCode(...e.option)}));return{id:n.toString(),summary:{isPublic:e.publicVoters,...Object(a.b)(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:i},results:k(t)}}function k(e){const{results:t,totalVoters:n,recentVoters:s,solution:i,solutionEntities:a}=e;return{totalVoters:n,recentVoterIds:s,results:t&&t.map(({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})),solution:i,...a&&{solutionEntities:a.map(B)}}}function E(e){if(!(e instanceof s.Api.MessageMediaWebPage&&e.webpage instanceof s.Api.WebPage))return;const{id:t,photo:n,document:i}=e.webpage;return{id:Number(t),...Object(a.b)(e.webpage,["url","displayUrl","siteName","title","description"]),photo:n&&n instanceof s.Api.Photo?{id:String(n.id),thumbnail:Object(c.e)(n.sizes),sizes:n.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(c.b)}:void 0,...i&&{hasDocument:!0}}}function R(e,t="file"){const{mimeType:n,attributes:i}=e,a=i.find(e=>e instanceof s.Api.DocumentAttributeFilename);if(a)return a.fileName;const r=n.split("/")[1];return`${t}${String(e.id)}.${r}`}function O(e,t,n,s,i,a,r,o,c,l){const d=h++,f=i&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:i,size:a}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return i.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:i,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:a}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=Object(u.a)(n,63);return{voice:{duration:t,waveform:s}}}return i.startsWith("audio/")?{audio:{mimeType:i,fileName:t,size:a,duration:200}}:{document:{mimeType:i,fileName:t,size:a,...s&&{previewBlobUrl:s}}}}(i),g="chatTypeChannel"===e.type;return{id:d,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...a&&{sticker:a},...r&&{video:r},...o&&T(o,d)},date:l||Math.round(Date.now()/1e3),isOutgoing:!g,senderId:p,...s&&{replyToMessageId:s},...c&&{groupedId:c,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...l&&{isScheduled:!0}}}function U(e,t){const n=h++,{content:s,chatId:i,id:a,senderId:r,groupedId:o,isInAlbum:c}=t,u=s.audio,l=e.id===p&&(i!==e.id||t.forwardInfo)&&!u;return{id:n,chatId:e.id,content:s,date:Math.round(Date.now()/1e3),isOutgoing:!l&&"chatTypeChannel"!==e.type,senderId:p,sendingState:"messageSendingStatePending",...r!==p&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:a,senderUserId:r}},groupedId:o,isInAlbum:c}}function T(e,t){return{poll:{id:t.toString(),summary:Object(a.b)(e.summary,["question","answers"]),results:{}}}}function B(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 D(e,t,n){const{channelId:s,replies:a,maxId:o,readMaxId:c,recentRepliers:u}=e;if(s===i.i)return;return{threadId:t,...n!==s?{chatId:Object(r.k)({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:o,lastReadInboxMessageId:c,...u&&{recentReplierIds:u.map(r.k)}}}},function(e,t,n){"use strict";(function(e){n.d(t,"m",(function(){return y})),n.d(t,"g",(function(){return b})),n.d(t,"e",(function(){return _})),n.d(t,"v",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"s",(function(){return P})),n.d(t,"q",(function(){return C})),n.d(t,"y",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"c",(function(){return E})),n.d(t,"a",(function(){return R})),n.d(t,"o",(function(){return O})),n.d(t,"p",(function(){return U})),n.d(t,"r",(function(){return T})),n.d(t,"u",(function(){return B})),n.d(t,"t",(function(){return D})),n.d(t,"j",(function(){return x})),n.d(t,"w",(function(){return j})),n.d(t,"n",(function(){return N})),n.d(t,"l",(function(){return F})),n.d(t,"k",(function(){return V})),n.d(t,"i",(function(){return L})),n.d(t,"x",(function(){return q})),n.d(t,"f",(function(){return H})),n.d(t,"h",(function(){return K}));var s=n(0),i=n(11),a=n(4),r=n(1),o=n(9),c=n(13),u=n(2),l=n(5),d=n(3),f=n(35),g=n(16),p=n(34),h=n(7);let m;function y(e){m=e}async function b({chat:e,threadId:t,...n}){const a=t===i.MAIN_THREAD_ID?s.Api.messages.GetHistory:s.Api.messages.GetReplies;let l;try{l=await Object(r.g)(new a({peer:Object(u.i)(e.id,e.accessHash),...t!==i.MAIN_THREAD_ID&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&m({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!l||l instanceof s.Api.messages.MessagesNotModified||!l.messages)return;z(l);const f=l.messages.map(o.b).filter(Boolean),g=l.users.map(c.a).filter(Boolean),p=l.chats.map(e=>Object(d.d)(e)).filter(Boolean),h=f.map(({threadInfo:e})=>e).filter(Boolean);let y;if(l.messages.length)if(l instanceof s.Api.messages.Messages)y=l.messages[l.messages.length-1].id;else if(n.offsetId&&l.offsetIdOffset){const e=l.messages.findIndex(e=>e.id===n.offsetId);l.messages.length-e+l.offsetIdOffset>=l.count&&(y=l.messages[l.messages.length-1].id)}return{messages:f,users:g,chats:p,threadInfos:h,firstMessageId:y}}async function _({chat:e,messageId:t}){const n="channel"===Object(u.s)(e.id),a=await Object(r.g)(n?new s.Api.channels.GetMessages({channel:Object(u.g)(e.id,e.accessHash),id:[new s.Api.InputMessageID({id:t})]}):new s.Api.messages.GetMessages({id:[new s.Api.InputMessageID({id:t})]}));if(!a||a instanceof s.Api.messages.MessagesNotModified)return;const l=a.messages[0];if(!l)return;if(l instanceof s.Api.MessageEmpty)return i.MESSAGE_DELETED;const d=l&&Object(o.b)(l);if(!d)return;l instanceof s.Api.Message&&Object(g.a)(l);return{message:d,users:a.users.map(c.a).filter(Boolean)}}let w=Promise.resolve();function v({chat:e,text:t,entities:n,replyingTo:i,attachment:c,sticker:d,gif:f,poll:g,isSilent:p,scheduledAt:h,groupedId:y,noWebPage:b},_){const v=Object(o.g)(e,t,n,i,c,d,f,g,y,h);m({"@type":v.isScheduled?"newScheduledMessage":"newMessage",id:v.id,chatId:e.id,message:v}),setTimeout(()=>{m({"@type":v.isScheduled?"updateScheduledMessage":"updateMessage",id:v.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})},1e3);const I=Object(u.r)();if(l.a.localMessages[I.toString()]=v,y)return function({chat:e,text:t,entities:n,replyingTo:i,attachment:o,groupedId:c,isSilent:l,scheduledAt:d},f,g,p){let h=-1;A[c]||(A[c]={counter:0,singleMediaByIndex:{}});h=A[c].counter++;const m=w;return w=(async()=>{let y;try{y=await S(g,o,p)}catch(e){return a.f&&console.warn(e),A[c].counter--,void await m}const b=await async function(e,t){const n=await Object(r.g)(new s.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof s.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof s.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaPhoto({id:new s.Api.InputPhoto({id:e,accessHash:t,fileReference:i})})}if(n instanceof s.Api.MessageMediaDocument&&n.document&&n.document instanceof s.Api.Document){const{document:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaDocument({id:new s.Api.InputDocument({id:e,accessHash:t,fileReference:i})})}return}(Object(u.i)(e.id,e.accessHash),y);if(await m,!b)return A[c].counter--,void(a.f&&console.warn("Failed to upload grouped media"));if(A[c].singleMediaByIndex[h]=new s.Api.InputSingleMedia({media:b,randomId:f,message:t||"",entities:n?n.map(u.n):void 0}),Object.keys(A[c].singleMediaByIndex).length{let o;if(c)try{o=await S(v,c,_)}catch(e){return a.f&&console.warn(e),void await P}else d?o=Object(u.h)(d):f?o=Object(u.h)(f):g&&(o=Object(u.j)(g,I));await P;const l=o?s.Api.messages.SendMedia:s.Api.messages.SendMessage;await Object(r.g)(new l({clearDraft:!0,message:t||"",entities:n?n.map(u.n):void 0,peer:Object(u.i)(e.id,e.accessHash),randomId:I,...p&&{silent:p},...h&&{scheduleDate:h},...i&&{replyToMsgId:i},...o&&{media:o},...b&&{noWebpage:b}}),!0)})(),w}const A={};async function I({chat:e,message:t,text:n,entities:i}){const a=1e3*t.date>Date.now(),o={content:{...t.content,...n&&{text:{text:n,entities:i}}}};m({"@type":a?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:o}),l.a.localMessages[t.id]={...t,...o};const c=i&&i.map(u.n);await Object(r.g)(new s.Api.messages.EditMessage({message:n||"",entities:c,peer:Object(u.i)(e.id,e.accessHash),id:t.id,...a&&{scheduleDate:t.date}}),!0)}async function P({chat:e,message:t,scheduledAt:n}){await Object(r.g)(new s.Api.messages.EditMessage({peer:Object(u.i)(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function S(t,n,i){const{filename:a,blobUrl:o,mimeType:c,quick:u,voice:l}=n,d=await Object(f.b)(o,a),g=e=>{i.isCanceled?g.isCanceled=!0:i(e,t.id)},h=await Object(r.i)(d,g),m=[new s.Api.DocumentAttributeFilename({fileName:a})];if(u){if(c.startsWith("image/"))return new s.Api.InputMediaUploadedPhoto({file:h});{const{width:e,height:t,duration:n}=u;void 0!==n&&m.push(new s.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(l){const{duration:t,waveform:n}=l,{data:i}=Object(p.a)(n,63);m.push(new s.Api.DocumentAttributeAudio({voice:!0,duration:t,waveform:e.from(i)}))}return new s.Api.InputMediaUploadedDocument({file:h,mimeType:c,attributes:m})}async function C({chat:e,messageId:t,isUnpin:n,isOneSide:i,isSilent:a}){await Object(r.g)(new s.Api.messages.UpdatePinnedMessage({peer:Object(u.i)(e.id,e.accessHash),id:t,...n&&{unpin:!0},...i&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function M({chat:e}){await Object(r.g)(new s.Api.messages.UnpinAllMessages({peer:Object(u.i)(e.id,e.accessHash)}),!0)}async function k({chat:e,messageIds:t,shouldDeleteForAll:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteMessages({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&m({"@type":"deleteMessages",ids:t,...i&&{chatId:e.id}})}async function E({chat:e,messageIds:t}){await Object(r.g)(new s.Api.messages.DeleteScheduledMessages({peer:Object(u.i)(e.id,e.accessHash),id:t}))&&m({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function R({chat:e,shouldDeleteForAll:t,maxId:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n}):new s.Api.messages.DeleteHistory({peer:Object(u.i)(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&m({"@type":"deleteHistory",chatId:e.id})}async function O({chat:e,threadId:t,maxId:n}){const a="channel"===Object(u.s)(e.id);a&&t===i.MAIN_THREAD_ID?await Object(r.g)(new s.Api.channels.ReadHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n})):a?await Object(r.g)(new s.Api.messages.ReadDiscussion({peer:Object(u.i)(e.id,e.accessHash),msgId:t,readMaxId:n})):await Object(r.g)(new s.Api.messages.ReadHistory({peer:Object(u.i)(e.id,e.accessHash),maxId:n})),t===i.MAIN_THREAD_ID?Object(h.u)(e):T({chat:e,threadId:t})}async function U({chat:e,messageIds:t}){const n="channel"===Object(u.s)(e.id);await Object(r.g)(n?new s.Api.channels.ReadMessageContents({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.ReadMessageContents({id:t})),m({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function T({chat:e,threadId:t}){const[n,i]=await Promise.all([Object(r.g)(new s.Api.messages.GetDiscussionMessage({peer:Object(u.i)(e.id,e.accessHash),msgId:t})),Object(r.g)(new s.Api.messages.GetReplies({peer:Object(u.i)(e.id,e.accessHash),msgId:t,limit:1}))]);if(!n||!n.messages.length)return;const a=Object(g.c)(n.messages[0]);if(!a)return;m({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:i instanceof s.Api.messages.ChannelMessages?i.count:void 0}});n.chats.map(e=>Object(d.d)(e)).filter(Boolean).forEach(e=>{m({"@type":"updateChat",id:e.id,chat:e})})}async function B({chatOrUser:e,type:t,query:n,topMessageId:i,minDate:a,maxDate:l,...d}){let f;switch(t){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"profilePhoto":f=new s.Api.InputMessagesFilterChatPhotos;break;case"text":default:f=new s.Api.InputMessagesFilterEmpty}const g=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:f,q:n||"",topMsgId:i,minDate:a,maxDate:l,...d}));if(!g||g instanceof s.Api.messages.MessagesNotModified||!g.messages)return;z(g);const p=g.messages.map(o.b).filter(Boolean),h=g.users.map(c.a).filter(Boolean);let m,y=p.length;return(g instanceof s.Api.messages.MessagesSlice||g instanceof s.Api.messages.ChannelMessages)&&(y=g.count,p.length&&(m=p[p.length-1].id)),{messages:p,users:h,totalCount:y,nextOffsetId:m}}async function D({query:e,offsetRate:t=0,limit:n,type:i="text",minDate:u,maxDate:l}){let f;switch(i){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||l&&u))return;f=new s.Api.InputMessagesFilterEmpty}const g=await Object(r.g)(new s.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new s.Api.InputPeerEmpty,limit:n,filter:f,folderId:a.a,minDate:u,maxDate:l}));if(!g||g instanceof s.Api.messages.MessagesNotModified||!g.messages)return;z({chats:g.chats,users:g.users,messages:g.messages});const p=g.chats.map(e=>Object(d.d)(e)).filter(Boolean),h=g.users.map(c.a).filter(Boolean),m=g.messages.map(o.b).filter(Boolean);let y,b=m.length;return(g instanceof s.Api.messages.MessagesSlice||g instanceof s.Api.messages.ChannelMessages)&&(b=g.count,m.length&&(y=m[m.length-1].id)),{messages:m,users:h,chats:p,totalCount:b,nextRate:"nextRate"in g&&g.nextRate?g.nextRate:y}}async function x({message:e}){const t=await Object(r.g)(new s.Api.messages.GetWebPagePreview({message:e}));return t&&Object(o.n)(t)}async function j({chat:t,messageId:n,options:i}){const{id:a,accessHash:o}=t;await Object(r.g)(new s.Api.messages.SendVote({peer:Object(u.i)(a,o),msgId:n,options:i.map(t=>e.from(t))}),!0)}async function N({chat:t,messageId:n,option:i,offset:a,limit:o,shouldResetVoters:l}){const{id:d,accessHash:f}=t,g=await Object(r.g)(new s.Api.messages.GetPollVotes({peer:Object(u.i)(d,f),id:n,...i&&{option:e.from(i)},...a&&{offset:a},...o&&{limit:o}}));if(!g)return;z({chats:[],users:g.users,messages:[]});const p=g.users.map(c.a).filter(Boolean),h=g.votes.map(e=>({userId:e.userId,date:e.date}));return{count:g.count,votes:h,users:p,nextOffset:g.nextOffset,shouldResetVoters:l}}async function F({fromChat:e,toChat:t,messages:n}){const i=n.map(({id:e})=>e),a=n.map(u.r);n.forEach((e,n)=>{const s=Object(o.f)(t,e);l.a.localMessages[String(a[n])]=s,m({"@type":"newMessage",id:s.id,chatId:t.id,message:s})}),await Object(r.g)(new s.Api.messages.ForwardMessages({fromPeer:Object(u.i)(e.id,e.accessHash),toPeer:Object(u.i)(t.id,t.accessHash),randomId:a,id:i}),!0)}async function V({chat:e,timestamp:t}){const n=await Object(r.g)(new s.Api.messages.GetHistory({peer:Object(u.i)(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof s.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function L({chat:e,hash:t=0}){const{id:n,accessHash:i}=e,a=await Object(r.g)(new s.Api.messages.GetScheduledHistory({peer:Object(u.i)(n,i),hash:t}));if(!a||a instanceof s.Api.messages.MessagesNotModified||!a.messages)return;z(a);const c=a.messages.map(o.b).filter(Boolean);return{messages:c,hash:Object(u.q)(c.map(e=>e.id))}}async function q({chat:e,ids:t}){const{id:n,accessHash:i}=e;await Object(r.g)(new s.Api.messages.SendScheduledMessages({peer:Object(u.i)(n,i),id:t}),!0)}function H({chat:e,message:t}){return Object(r.g)(new s.Api.channels.ExportMessageLink({id:t.id,channel:Object(u.g)(e.id,e.accessHash),...t.isInAlbum&&{grouped:!0},...t.threadInfo&&t.threadInfo.topMessageId!==t.id&&{thread:!0}}))}function z(e){e.users.forEach(e=>{e instanceof s.Api.User&&(l.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(l.a.chats[e.id]=e)}),e.messages.forEach(e=>{(e instanceof s.Api.Message&&Object(u.t)(e)||e instanceof s.Api.MessageService&&Object(u.u)(e))&&Object(g.a)(e)})}async function K({chat:e}){const t=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:new s.Api.InputMessagesFilterPinned,q:"",limit:a.s}));if(!t||t instanceof s.Api.messages.MessagesNotModified||!t.messages)return;z(t);return{messages:t.messages.map(o.b).filter(Boolean),users:t.users.map(c.a).filter(Boolean),chats:t.chats.map(e=>Object(d.d)(e)).filter(Boolean)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";var s=n(65);n.o(s,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return s.ApiMediaFormat})),n.o(s,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return s.ApiMessageEntityTypes})),n.o(s,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return s.MAIN_THREAD_ID})),n.o(s,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return s.MESSAGE_DELETED}));var i=n(66);n.o(i,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return i.ApiMediaFormat})),n.o(i,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return i.ApiMessageEntityTypes})),n.o(i,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return i.MAIN_THREAD_ID})),n.o(i,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return i.MESSAGE_DELETED}));var a=n(67);n.d(t,"ApiMessageEntityTypes",(function(){return a.a})),n.d(t,"MAIN_THREAD_ID",(function(){return a.b})),n.d(t,"MESSAGE_DELETED",(function(){return a.c}));var r=n(68);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat}));var o=n(69);n.d(t,"ApiMediaFormat",(function(){return o.a}));n(70),n(71)},function(e,t,n){"use strict";(function(e){var s=n(73),i=n(74),a=n(75);function r(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(s)return V(e).length;t=(""+t).toLowerCase(),s=!0}}function h(e,t,n){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function m(e,t,n){var s=e[t];e[t]=e[n],e[n]=s}function y(e,t,n,s,i){if(0===e.length)return-1;if("string"==typeof n?(s=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,s)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,s,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,s,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,s,i){var a,r=1,o=e.length,c=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;r=2,o/=2,c/=2,n/=2}function u(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(i){var l=-1;for(a=n;ao&&(n=o-c),a=n;a>=0;a--){for(var d=!0,f=0;fi&&(s=i):s=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");s>a/2&&(s=a/2);for(var r=0;r>8,i=n%256,a.push(i),a.push(s);return a}(t,e.length-n),e,n,s)}function S(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function C(e,t,n){n=Math.min(e.length,n);for(var s=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+d<=n)switch(d){case 1:u<128&&(l=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(l=c);break;case 3:a=e[i+1],r=e[i+2],128==(192&a)&&128==(192&r)&&(c=(15&u)<<12|(63&a)<<6|63&r)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:a=e[i+1],r=e[i+2],o=e[i+3],128==(192&a)&&128==(192&r)&&128==(192&o)&&(c=(15&u)<<18|(63&a)<<12|(63&r)<<6|63&o)>65535&&c<1114112&&(l=c)}null===l?(l=65533,d=1):l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|1023&l),s.push(l),i+=d}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",s=0;for(;s0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,s,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||n>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=n)return 0;if(s>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(s>>>=0),r=(n>>>=0)-(t>>>=0),o=Math.min(a,r),u=this.slice(s,i),l=e.slice(t,n),d=0;di)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var a=!1;;)switch(s){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return v(this,e,t,n);case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(e,t,n){var s="";n=Math.min(e.length,n);for(var i=t;is)&&(n=s);for(var i="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,n,s,i,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function T(e,t,n,s){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i>>8*(s?i:1-i)}function B(e,t,n,s){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i>>8*(s?i:3-i)&255}function D(e,t,n,s,i,a){if(n+s>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,s,a){return a||D(e,0,n,4),i.write(e,t,n,s,23,4),n+4}function j(e,t,n,s,a){return a||D(e,0,n,8),i.write(e,t,n,s,52,8),n+8}c.prototype.slice=function(e,t){var n,s=this.length;if((e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(t=void 0===t?s:~~t)<0?(t+=s)<0&&(t=0):t>s&&(t=s),t0&&(i*=256);)s+=this[e+--t]*i;return s},c.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||O(e,t,this.length);for(var s=this[e],i=1,a=0;++a=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||O(e,t,this.length);for(var s=t,i=1,a=this[e+--s];s>0&&(i*=256);)a+=this[e+--s]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,s){(e=+e,t|=0,n|=0,s)||U(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):B(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);U(this,e,t,n,i-1,-i)}var a=0,r=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);U(this,e,t,n,i-1,-i)}var a=n-1,r=1,o=0;for(this[t+a]=255&e;--a>=0&&(r*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/r>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):B(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,s){if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(a<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(r+1===s){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function L(e){return s.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,s){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(44))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return o}));var s=n(0);function i(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:i,notifySettings:{silent:r,muteUntil:o}}=e,c=r||"number"==typeof o&&Date.now()<1e3*o;return{...a(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isMuted:c,...i&&{botDescription:i.description}}}}function a(e){if(!(e instanceof s.Api.User))return;const{id:t,firstName:n,lastName:i}=e,a=e.photo instanceof s.Api.UserProfilePhoto?String(e.photo.photoId):void 0;return{id:t,isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:r(e),...n&&{firstName:n},...i&&{lastName:i},username:e.username||"",phoneNumber:e.phone||"",status:o(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a}}}function r(e){return e.bot?"userTypeBot":e.deleted?"userTypeDeleted":"userTypeRegular"}function o(e){return!e||e instanceof s.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof s.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof s.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof s.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof s.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}},function(e,t,n){"use strict";function s(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function i(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function a(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a}))},function(e,t,n){(function(e){var s,i=function(e){"use strict";var t=1e7,n=9007199254740992,s=d(n),a="function"==typeof BigInt;function r(e,t,n,s){return void 0===e?r[0]:void 0!==t&&(10!=+t||n)?V(e,t,n,s):K(e)}function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function c(e){this.value=e,this.sign=e<0,this.isSmall=!0}function u(e){this.value=e}function l(e){return-n0?Math.floor(e):Math.ceil(e)}function m(e,n){var s,i,a=e.length,r=n.length,o=new Array(a),c=0,u=t;for(i=0;i=u?1:0,o[i]=s-c*u;for(;i0&&o.push(c),o}function y(e,t){return e.length>=t.length?m(e,t):m(t,e)}function b(e,n){var s,i,a=e.length,r=new Array(a),o=t;for(i=0;i0;)r[i++]=n%o,n=Math.floor(n/o);return r}function _(e,t){var n,s,i=e.length,a=t.length,r=new Array(i),o=0;for(n=0;n0;)r[i++]=c%o,c=Math.floor(c/o);return r}function I(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function P(e,n,s){return new o(e=0;--n)i=(a=1e7*i+e[n])-(s=h(a/t))*t,o[n]=0|s;return[o,0|i]}function M(e,n){var s,i=K(n);if(a)return[new u(e.value/i.value),new u(e.value%i.value)];var l,m=e.value,y=i.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new c(h(m/y)),new c(m%y)]:[r[0],e];if(i.isSmall){if(1===y)return[e,r[0]];if(-1==y)return[e.negate(),r[0]];var b=Math.abs(y);if(b=0;i--){for(s=g-1,b[i+d]!==m&&(s=Math.floor((b[i+d]*g+b[i+d-1])/m)),a=0,r=0,c=_.length,o=0;oc&&(i=1e7*(i+1)),n=Math.ceil(i/a);do{if(k(r=A(t,n),l)<=0)break;n--}while(n);u.push(n),l=_(l,r)}return u.reverse(),[f(u),f(l)]}(m,y))[0];var I=e.sign!==i.sign,P=s[1],S=e.sign;return"number"==typeof l?(I&&(l=-l),l=new c(l)):l=new o(l,I),"number"==typeof P?(S&&(P=-P),P=new c(P)):P=new o(P,S),[l,P]}function k(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function E(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function R(e,t){for(var n,s,a,r=e.prev(),o=r,c=0;o.isEven();)o=o.divide(2),c++;e:for(s=0;s=0?s=_(e,t):(s=_(t,e),n=!n),"number"==typeof(s=f(s))?(n&&(s=-s),new c(s)):new o(s,n)}(n,s,this.sign)},o.prototype.minus=o.prototype.subtract,c.prototype.subtract=function(e){var t=K(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var s=t.value;return t.isSmall?new c(n-s):w(s,Math.abs(n),n>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-K(e).value)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},o.prototype.abs=function(){return new o(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},o.prototype.multiply=function(e){var n,s,i,a=K(e),c=this.value,u=a.value,l=this.sign!==a.sign;if(a.isSmall){if(0===u)return r[0];if(1===u)return this;if(-1===u)return this.negate();if((n=Math.abs(u))0?function e(t,n){var s=Math.max(t.length,n.length);if(s<=30)return v(t,n);s=Math.ceil(s/2);var i=t.slice(s),a=t.slice(0,s),r=n.slice(s),o=n.slice(0,s),c=e(a,o),u=e(i,r),l=e(y(a,i),y(o,r)),d=y(y(c,I(_(_(l,c),u),s)),I(u,2*s));return g(d),d}(c,u):v(c,u),l)},o.prototype.times=o.prototype.multiply,c.prototype._multiplyBySmall=function(e){return l(e.value*this.value)?new c(e.value*this.value):P(Math.abs(e.value),d(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return 0===e.value?r[0]:1===e.value?this:-1===e.value?this.negate():P(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return K(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*K(e).value)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(S(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return l(e)?new c(e):new o(S(d(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},o.prototype.divmod=function(e){var t=M(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return M(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/K(e).value)},c.prototype.over=c.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return M(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%K(e).value)},c.prototype.remainder=c.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t,n,s,i=K(e),a=this.value,o=i.value;if(0===o)return r[1];if(0===a)return r[0];if(1===a)return r[1];if(-1===a)return i.isEven()?r[1]:r[-1];if(i.sign)return r[0];if(!i.isSmall)throw new Error("The exponent "+i.toString()+" is too large.");if(this.isSmall&&l(t=Math.pow(a,o)))return new c(h(t));for(n=this,s=r[1];!0&o&&(s=s.times(n),--o),0!==o;)o/=2,n=n.square();return s},c.prototype.pow=o.prototype.pow,u.prototype.pow=function(e){var t=K(e),n=this.value,s=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(s===i)return r[1];if(n===i)return r[0];if(n===a)return r[1];if(n===BigInt(-1))return t.isEven()?r[1]:r[-1];if(t.isNegative())return new u(i);for(var c=this,l=r[1];(s&a)===a&&(l=l.times(c),--s),s!==i;)s/=o,c=c.square();return l},o.prototype.modPow=function(e,t){if(e=K(e),(t=K(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var n=r[1],s=this.mod(t);for(e.isNegative()&&(e=e.multiply(r[-1]),s=s.modInv(t));e.isPositive();){if(s.isZero())return r[0];e.isOdd()&&(n=n.multiply(s).mod(t)),e=e.divide(2),s=s.square().mod(t)}return n},u.prototype.modPow=c.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=K(e),n=this.value,s=t.value;return t.isSmall?1:k(n,s)},c.prototype.compareAbs=function(e){var t=K(e),n=Math.abs(this.value),s=t.value;return t.isSmall?n===(s=Math.abs(s))?0:n>s?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,n=K(e).value;return(t=t>=0?t:-t)===(n=n>=0?n:-n)?0:t>n?1:-1},o.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=K(e),n=this.value,s=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:k(n,s)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=K(e),n=this.value,s=t.value;return t.isSmall?n==s?0:n>s?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=K(e).value;return t===n?0:t>n?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return 0==(1&this.value[0])},c.prototype.isEven=function(){return 0==(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},o.prototype.isOdd=function(){return 1==(1&this.value[0])},c.prototype.isOdd=function(){return 1==(1&this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},o.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,o.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,o.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},o.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},o.prototype.isDivisibleBy=function(e){var t=K(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(e){var t=E(this);if(void 0!==t)return t;var n=this.abs(),s=n.bitLength();if(s<=64)return R(n,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var a=Math.log(2)*s.toJSNumber(),r=Math.ceil(!0===e?2*Math.pow(a,2):a),o=[],c=0;c-n?new c(e-1):new o(s,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var O=[1];2*O[O.length-1]<=t;)O.push(2*O[O.length-1]);var U=O.length,T=O[U-1];function B(e){return Math.abs(e)<=t}function D(e,t,n){t=K(t);for(var s=e.isNegative(),a=t.isNegative(),r=s?e.not():e,o=a?t.not():t,c=0,u=0,l=null,d=null,f=[];!r.isZero()||!o.isZero();)c=(l=M(r,T))[1].toJSNumber(),s&&(c=T-1-c),u=(d=M(o,T))[1].toJSNumber(),a&&(u=T-1-u),r=l[0],o=d[0],f.push(n(c,u));for(var g=0!==n(s?1:0,a?1:0)?i(-1):i(0),p=f.length-1;p>=0;p-=1)g=g.multiply(T).add(i(f[p]));return g}o.prototype.shiftLeft=function(e){var t=K(e).toJSNumber();if(!B(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=U;)n=n.multiply(T),t-=U-1;return n.multiply(O[t])},u.prototype.shiftLeft=function(e){return e=K(e),new u(this.value<=U;){if(s.isZero()||s.isNegative()&&s.isUnit())return s;s=(t=M(s,T))[1].isNegative()?t[0].prev():t[0],n-=U-1}return(t=M(s,O[n]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=function(e){return e=K(e),new u(this.value>>e.value)},c.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=o.prototype.not,o.prototype.and=function(e){return D(this,e,(function(e,t){return e&t}))},u.prototype.and=c.prototype.and=o.prototype.and,o.prototype.or=function(e){return D(this,e,(function(e,t){return e|t}))},u.prototype.or=c.prototype.or=o.prototype.or,o.prototype.xor=function(e){return D(this,e,(function(e,t){return e^t}))},u.prototype.xor=c.prototype.xor=o.prototype.xor;function x(e){var n=e.value,s="number"==typeof n?n|1<<30:"bigint"==typeof n?n|BigInt(1<<30):n[0]+n[1]*t|1073758208;return s&-s}function j(e,t){return e=K(e),t=K(t),e.greater(t)?e:t}function N(e,t){return e=K(e),t=K(t),e.lesser(t)?e:t}function F(e,t){if(e=K(e).abs(),t=K(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n,s,i=r[1];e.isEven()&&t.isEven();)n=N(x(e),x(t)),e=e.divide(n),t=t.divide(n),i=i.multiply(n);for(;e.isEven();)e=e.divide(x(e));do{for(;t.isEven();)t=t.divide(x(t));e.greater(t)&&(s=t,t=e,e=s),t=t.subtract(e)}while(!t.isZero());return i.isUnit()?e:e.multiply(i)}o.prototype.bitLength=function(){var e=this;return e.compareTo(i(0))<0&&(e=e.negate().subtract(i(1))),0===e.compareTo(i(0))?i(0):i(function e(t,n){if(n.compareTo(t)<=0){var s=e(t,n.square(n)),a=s.p,r=s.e,o=a.multiply(n);return o.compareTo(t)<=0?{p:o,e:2*r+1}:{p:a,e:2*r}}return{p:i(1),e:0}}(e,i(2)).e).add(i(1))},u.prototype.bitLength=c.prototype.bitLength=o.prototype.bitLength;var V=function(e,t,n,s){n=n||"0123456789abcdefghijklmnopqrstuvwxyz",e=String(e),s||(e=e.toLowerCase(),n=n.toLowerCase());var i,a=e.length,r=Math.abs(t),o={};for(i=0;i=r)){if("1"===l&&1===r)continue;throw new Error(l+" is not a valid digit in base "+t+".")}}t=K(t);var c=[],u="-"===e[0];for(i=u?1:0;i"!==e[i]&&i=0;s--)i=i.add(e[s].times(a)),a=a.times(t);return n?i.negate():i}function q(e,t){if((t=i(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var n=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return n.unshift([1]),{value:[].concat.apply([],n),isNegative:!1}}var s=!1;if(e.isNegative()&&t.isPositive()&&(s=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:s};for(var a,r=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var c=a.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),r.push(c.toJSNumber())}return r.push(o.toJSNumber()),{value:r.reverse(),isNegative:s}}function H(e,t,n){var s=q(e,t);return(s.isNegative?"-":"")+s.value.map((function(e){return function(e,t){return e<(t=t||"0123456789abcdefghijklmnopqrstuvwxyz").length?t[e]:"<"+e+">"}(e,n)})).join("")}function z(e){if(l(+e)){var t=+e;if(t===h(t))return a?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var n="-"===e[0];n&&(e=e.slice(1));var s=e.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var i=s[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==h(i)||!l(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var r=s[0],d=r.indexOf(".");if(d>=0&&(i-=r.length-d-1,r=r.slice(0,d)+r.slice(d+1)),i<0)throw new Error("Cannot include negative exponent part for integers");e=r+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(a)return new u(BigInt(n?"-"+e:e));for(var f=[],p=e.length,m=p-7;p>0;)f.push(+e.slice(m,p)),(m-=7)<0&&(m=0),p-=7;return g(f),new o(f,n)}function K(e){return"number"==typeof e?function(e){if(a)return new u(BigInt(e));if(l(e)){if(e!==h(e))throw new Error(e+" is not an integer.");return new c(e)}return z(e.toString())}(e):"string"==typeof e?z(e):"bigint"==typeof e?new u(e):e}o.prototype.toArray=function(e){return q(this,e)},c.prototype.toArray=function(e){return q(this,e)},u.prototype.toArray=function(e){return q(this,e)},o.prototype.toString=function(e,t){if(void 0===e&&(e=10),10!==e)return H(this,e,t);for(var n,s=this.value,i=s.length,a=String(s[--i]);--i>=0;)n=String(s[i]),a+="0000000".slice(n.length)+n;return(this.sign?"-":"")+a},c.prototype.toString=function(e,t){return void 0===e&&(e=10),10!=e?H(this,e,t):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=o.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},o.prototype.valueOf=function(){return parseInt(this.toString(),10)},o.prototype.toJSNumber=o.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var G=0;G<1e3;G++)r[G]=K(G),G>0&&(r[-G]=K(-G));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=j,r.min=N,r.gcd=F,r.lcm=function(e,t){return e=K(e).abs(),t=K(t).abs(),e.divide(F(e,t)).multiply(t)},r.isInstance=function(e){return e instanceof o||e instanceof c||e instanceof u},r.randBetween=function(e,n,s){e=K(e),n=K(n);var i=s||Math.random,a=N(e,n),o=j(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var c=q(o,t).value,u=[],l=!0,d=0;d{r.resolve=e,r.reject=t})}function l(e=!1){return o({...y("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise((e,t)=>{r.resolve=e,r.reject=t})}function d(e){return o({...y("authorizationStateWaitPassword"),hint:e}),new Promise(e=>{r.resolve=e})}function f(){return o(y("authorizationStateWaitRegistration")),new Promise(e=>{r.resolve=e})}function g(e){return o({...y("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise((e,t)=>{r.reject=t})}function p(e){let t;if(e instanceof s.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=a[e.message];t||(t="Unexpected Error",i.f&&console.error(e)),o({"@type":"updateAuthorizationError",message:t})}function h(e){o({...y("authorizationStateReady"),sessionId:e})}function m(e){o({"@type":"updateCurrentUser",currentUser:e})}function y(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function b(e){r.resolve&&r.resolve(e)}function _(e){r.resolve&&r.resolve(e)}function w(e){r.resolve&&r.resolve(e)}function v(e){const{firstName:t,lastName:n}=e;r.resolve&&r.resolve([t,n])}function A(){r.reject&&r.reject(new Error("RESTART_AUTH"))}function I(){r.reject&&r.reject(new Error("RESTART_AUTH_WITH_QR"))}},function(e,t,n){"use strict";function s(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function i(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:i,classType:a,...r}=e;return r}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i}))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return l})),n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return f}));var s=n(0),i=n(21),a=n(18);function r(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const o={w:100,h:100};function c(e,t){if(!e||!e.length)return;const n=e.find(e=>e instanceof s.Api.PhotoStrippedSize);if(!n)return;const r=e.filter(e=>e instanceof s.Api.PhotoSize),{w:c,h:u}=r&&r.length?r[r.length-1]:o,{bytes:l}=n;return{dataUri:Object(a.a)(t&&"image/jpeg"!==t?l:Object(i.strippedPhotoToJpg)(l),void 0,t),width:c,height:u}}function u(e){const{w:t,h:n,bytes:s}=e;return{dataUri:Object(a.a)(s,void 0,"image/webp"),width:t,height:n}}function l(e,t){const{w:n,h:s}=t;return{dataUri:"data:image/svg+xml;utf8,"+r(e.bytes,n,s),width:n,height:s}}function d(e){const t=e.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(f);return{id:String(e.id),thumbnail:c(e.sizes),sizes:t}}function f(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}},function(e,t,n){const s=n(6),{serializeBytes:i,serializeDate:a}=n(45);e.exports={constructors:s,requests:s,patched:null,serializeBytes:i,serializeDate:a}},function(e,t,n){(function(t){const{constructors:s}=n(20),i=(new RegExp("@|(?:https?:\\/\\/)?(?:www\\.)?(?:telegram\\.(?:me|dog)|t\\.me)\\/(@|joinchat\\/)?"),t.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex")),a=t.from("ffd9","hex");new RegExp("tg:\\/\\/(join)\\?invite="),new RegExp("^([a-z]((?!__)[\\w\\d]){3,30}[a-z\\d]|gif|vid|pic|bing|wiki|imdb|bold|vote|like|coub)$");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(null==e)return null;if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error("Invalid message type: "+e.constructor.name)},getInputPeer:function e(t,n=!0,i=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof s.User){if(t.isSelf&&n)return new s.InputPeerSelf;if(void 0===t.accessHash&&i)throw new Error("User without accessHash or min info cannot be input");return new s.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof s.Chat||t instanceof s.ChatEmpty||t instanceof s.ChatForbidden)return new s.InputPeerChat({chatId:t.id});if(t instanceof s.Channel){if(void 0===t.accessHash&&i)throw new TypeError("Channel without accessHash or min info cannot be input");return new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof s.ChannelForbidden?new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof s.InputUser?new s.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof s.InputChannel?new s.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof s.UserEmpty?new s.InputPeerEmpty:t instanceof s.UserFull?e(t.user):t instanceof s.ChatFull?new s.InputPeerChat({chatId:t.id}):t instanceof s.PeerChat?new s.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof s.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof s.Chat||e instanceof s.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=1572864e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const n=t.from(i);return n[164]=e[1],n[166]=e[2],t.concat([n,e.slice(3),a])},getDC:function(e,t=!1){switch(e){case 1:return{id:1,ipAddress:"pluto.web.telegram.org",port:443};case 2:return{id:2,ipAddress:"venus.web.telegram.org",port:443};case 3:return{id:3,ipAddress:"aurora.web.telegram.org",port:443};case 4:return{id:4,ipAddress:"vesta.web.telegram.org",port:443};case 5:return{id:5,ipAddress:"flora.web.telegram.org",port:443};default:throw new Error("Cannot find the DC with the ID of "+e)}}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return u}));var s=n(0),i=n(4),a=n(19),r=n(5);function o(e){if(e instanceof s.Api.DocumentEmpty)return;const t=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeSticker);if(!t)return;const n=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeImageSize),r=t.stickerset,o=t.alt,c="application/x-tgsticker"===e.mimeType,u=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoCachedSize),l=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoPathSize),d=u?Object(a.c)(u):l&&n?Object(a.d)(l,n):void 0,{w:f,h:g}=u||n||{};return{id:String(e.id),stickerSetId:r.id?String(r.id):i.r,stickerSetAccessHash:String(r.accessHash),emoji:o,isAnimated:c,width:f,height:g,thumbnail:d}}function c(e){const{archived:t,animated:n,installedDate:s,id:i,accessHash:a,title:r,thumb:o,count:c,hash:u}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(i),accessHash:String(a),title:r,hasThumbnail:Boolean(o),count:c,hash:u}}function u(e){const t=c(e.set),n=e instanceof s.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach(e=>{if(e instanceof s.Api.Document){const n=o(e);n&&(t.covers.push(n),r.a.documents[String(e.id)]=e)}}),t}},function(e,t){class n extends Error{constructor(){super("The read operation was cancelled.")}}class s extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert("Missing MTProto Entity: Please, make sure to add TL definition for ID "+e),this.invalidConstructorId=e,this.remaining=t}}class i extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t=null;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class r extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=" Caused by "+e.className,super(n),this.message=n,this.code=t}}var c,u,l;l={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(u="ErrorMessages")in(c=o)?Object.defineProperty(c,u,{value:l,enumerable:!0,configurable:!0,writable:!0}):c[u]=l,e.exports={ReadCancelledError:n,TypeNotFoundError:s,InvalidChecksumError:i,InvalidBufferError:a,SecurityError:r,CdnFileTamperedError:class extends r{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u}));var s=n(0),i=n(9),a=n(14);function r(e){if(e instanceof s.Api.WallPaperNoFile)return;const{slug:t}=e,n=Object(i.a)(e.document);return n?{slug:t,document:n}:void 0}function o(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...Object(a.b)(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function c(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}function u(e){let t,n,i,a,r;return e.forEach(e=>{e instanceof s.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof s.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof s.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof s.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof s.Api.PrivacyValueAllowUsers?n=e.users:e instanceof s.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof s.Api.PrivacyValueAllowChatParticipants?i=e.chats.map(e=>-e):e instanceof s.Api.PrivacyValueDisallowChatParticipants&&(r=e.chats.map(e=>-e))}),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:i||[],blockUserIds:a||[],blockChatIds:r||[]}}},function(e,t,n){const{TypeNotFoundError:s}=n(23),{coreObjects:i}=n(51),{tlobjects:a}=n(53),{readBigIntFromBuffer:r}=n(8);e.exports=class{constructor(e){this.stream=e,this._last=null,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error("Invalid boolean code "+e.toString("16"))}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=a[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;ne instanceof s.Api.User).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}),n.filter(e=>e instanceof s.Api.Chat||e instanceof s.Api.Channel).map(e=>Object(r.d)(e)).forEach(e=>{e&&h({"@type":"updateChat",id:e.id,chat:e})})),e instanceof s.Api.UpdateNewScheduledMessage?h({"@type":y.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):h({"@type":y.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof s.Api.MessageService){const{action:n}=e.message;if(n instanceof s.Api.MessageActionChatEditTitle)h({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof s.Api.MessageActionChatEditPhoto){const i=Object(c.c)(n.photo),a=Object(r.e)(i),o=Math.abs(Object(f.c)(e.message));u.a.chats[o]&&(u.a.chats[o].photo=i),Object(f.b)(n.photo),a&&h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof s.Api.Photo&&{newProfilePhoto:Object(p.a)(n.photo)}})}else if(n instanceof s.Api.MessageActionChatDeletePhoto){const n=Math.abs(Object(f.c)(e.message));u.a.chats[n]&&(u.a.chats[n].photo=new s.Api.ChatPhotoEmpty),h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof s.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&e.id===n.userId)&&h({"@type":"updateChatLeave",id:t.chatId}):n instanceof s.Api.MessageActionChatAddUser&&e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&n.users.includes(e.id))&&h({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof s.Api.UpdateEditMessage||e instanceof s.Api.UpdateEditChannelMessage){if(e.message instanceof s.Api.MessageEmpty)return void(d.f&&console.error("Unexpected update:",e.className,e));e.message instanceof s.Api.Message&&Object(c.t)(e.message)&&Object(f.a)(e.message);const t=Object(a.b)(e.message);h({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof s.Api.UpdateDeleteMessages)h({"@type":"deleteMessages",ids:e.messages});else if(e instanceof s.Api.UpdateDeleteScheduledMessages)h({"@type":"deleteScheduledMessages",ids:e.messages,chatId:Object(r.j)(e.peer)});else if(e instanceof s.Api.UpdateDeleteChannelMessages){const t=Object(r.k)({channelId:e.channelId}),n=e.messages,i=n.filter(e=>u.a.messages[`${t}-${e}`]),a=n.filter(e=>!u.a.messages[`${t}-${e}`]),o=n.map(e=>{const n=u.a.messages[`${t}-${e}`];return n&&n instanceof s.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0}).filter(Boolean);i.length&&h({"@type":"deleteMessages",ids:i,chatId:t}),o.length&&h({"@type":"deleteProfilePhotos",ids:o,chatId:t}),a.length&&setTimeout(()=>{h({"@type":"deleteMessages",ids:a,chatId:t})},1e3)}else if((t instanceof s.Api.messages.SendMessage||t instanceof s.Api.messages.SendMedia||t instanceof s.Api.messages.SendMultiMedia||t instanceof s.Api.messages.ForwardMessages)&&(e instanceof s.Api.UpdateMessageID||e instanceof s.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const i=n&&u.a.localMessages[n.toString()];if(!i)throw new Error("Local message not found");let r;if(e instanceof s.Api.UpdateShortSentMessage){i.content.text&&e.entities&&(r={text:Object(a.j)(i.content.text.text,e.entities)}),e.media&&(r={...r,...Object(a.i)(e.media)});const t=Object(c.m)(e.id,i.chatId,e);Object(c.t)(t)&&Object(f.a)(t)}y.add(e.id);const o="date"in e&&1e3*e.dateString.fromCharCode(...e))});else if(e instanceof s.Api.UpdateChannelMessageViews)h({"@type":"updateMessage",chatId:Object(r.k)({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof s.Api.UpdateReadHistoryInbox)h({"@type":"updateChatInbox",id:Object(r.k)(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadHistoryOutbox)h({"@type":"updateChat",id:Object(r.k)(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateReadChannelInbox)h({"@type":"updateChat",id:Object(r.k)({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadChannelOutbox)h({"@type":"updateChat",id:Object(r.k)({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateDialogPinned&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChatPinned",id:Object(r.k)(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof s.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter(e=>e instanceof s.Api.DialogPeer).map(e=>Object(r.k)(e.peer)):[];h({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof s.Api.UpdateFolderPeers)e.folderPeers.forEach(e=>{const{folderId:t,peer:n}=e;h({"@type":"updateChatListType",id:Object(r.k)(n),folderId:t})});else if(e instanceof s.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Object(r.a)(n):void 0;h({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof s.Api.UpdateDialogFilterOrder)h({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof s.Api.UpdateChatParticipants){const t=Object(r.h)(e.participants);h({"@type":"updateChatMembers",id:Object(r.k)({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof s.Api.UpdateChatParticipantAdd){const t=Object(r.g)(Object(i.b)(e,["userId","inviterId","date"]));h({"@type":"updateChatMembers",id:Object(r.k)({chatId:e.chatId}),addedMember:t})}else if(e instanceof s.Api.UpdateChatParticipantDelete){const{userId:t}=e;h({"@type":"updateChatMembers",id:Object(r.k)({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof s.Api.UpdatePinnedMessages||e instanceof s.Api.UpdatePinnedChannelMessages){const t=e instanceof s.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId},n=Object(r.k)(t);h({"@type":"updatePinnedIds",chatId:n,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof s.Api.UpdateNotifySettings&&e.peer instanceof s.Api.NotifyPeer){const{silent:t,muteUntil:n}=e.notifySettings;h({"@type":"updateChat",id:Object(r.k)(e.peer.peer),chat:{isMuted:t||"number"==typeof n&&Date.now()<1e3*n}})}else if(e instanceof s.Api.UpdateUserTyping||e instanceof s.Api.UpdateChatUserTyping){const t=e instanceof s.Api.UpdateUserTyping?e.userId:Object(r.k)({chatId:e.chatId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.i)(e)})}else if(e instanceof s.Api.UpdateChannelUserTyping){const t=Object(r.k)({channelId:e.channelId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.i)(e)})}else if(e instanceof s.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find(e=>e instanceof s.Api.Channel||e instanceof s.Api.ChannelForbidden);if(n instanceof s.Api.Channel){const t=Object(r.d)(n);t&&(h({"@type":"updateChat",id:t.id,chat:t}),h({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:Object(r.k)({channelId:e.channelId})}))}else if(n instanceof s.Api.ChannelForbidden){const t=Object(r.k)({channelId:e.channelId});h({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),h({"@type":"updateChatLeave",id:t})}else 0===t.length&&h({"@type":"resetMessages",id:Object(r.k)({chatId:e.channelId})})}else if(e instanceof s.Api.UpdateDialogUnreadMark&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChat",id:Object(r.k)(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof s.Api.UpdateChatDefaultBannedRights)h({"@type":"updateChat",id:Object(r.k)(e.peer),chat:{defaultBannedRights:Object(l.b)(e.defaultBannedRights)}});else if(e instanceof s.Api.UpdateUserStatus){const{userId:t,status:n}=e;h({"@type":"updateUserStatus",userId:t,status:Object(o.c)(n)})}else if(e instanceof s.Api.UpdateUserName){const t=u.a.users[e.userId],n=t&&t.mutualContact&&!t.self?Object(i.b)(e,["username"]):Object(i.b)(e,["firstName","lastName","username"]);h({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof s.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=Object(r.e)(n);u.a.users[t]&&(u.a.users[t].photo=n),h({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof s.Api.UpdateUserPhone){const{userId:t,phone:n}=e;h({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof s.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter(e=>e instanceof s.Api.User&&!e.contact).forEach(e=>{h({"@type":"deleteUser",id:e.id})}),t.filter(e=>e instanceof s.Api.User&&e.contact).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}))}else if(e instanceof s.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:i}}=e,a="NotifyUsers"===i?"contact":"NotifyChats"===i?"group":"NotifyBroadcasts"===i?"broadcast":void 0;if(!a)return;h({"@type":"updateNotifySettings",peerType:a,isSilent:Boolean(n||"number"==typeof s&&Date.now()<1e3*s),isShowPreviews:Boolean(t)})}else if(e instanceof s.Api.UpdatePeerBlocked)h({"@type":"updatePeerBlocked",id:Object(r.k)(e.peerId),isBlocked:e.blocked});else if(e instanceof s.Api.UpdatePrivacy){const t=Object(g.c)(e.key);t&&h({"@type":"updatePrivacy",key:t,rules:Object(g.d)(e.rules)})}else if(e instanceof s.Api.UpdateContactsReset)h({"@type":"updateResetContactList"});else if(e instanceof s.Api.UpdateFavedStickers)h({"@type":"updateFavoriteStickers"});else if(d.f){const t="object"==typeof e&&"className"in e?e.className:e;console.warn("[GramJs/updater] Unexpected update:",t)}}},function(e,t,n){const{RPCError:s}=n(37),{rpcErrorRe:i}=n(48);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of i){const i=e.errorMessage.match(n);if(i){return new s({request:t,capture:2===i.length?parseInt(i[1]):null})}}return new s(e.errorMessage,t)},...n(23),...n(37),...n(48)}},function(e,t,n){"use strict";function s(e,t,n=!0){let s,i,a;return(...r)=>{i=!0,a=r,s||(n&&(i=!1,e(...a)),s=self.setInterval(()=>{if(!i)return self.clearInterval(s),void(s=void 0);i=!1,e(...a)},t))}}function i(e){return a(r,e)}function a(e,t){let n,s=!1;return(...i)=>{n=i,s||(s=!0,e(()=>{s=!1,t(...n)}))}}function r(e){Promise.resolve().then(e)}n.d(t,"b",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const o=e=>new Promise(t=>{setTimeout(()=>t(),e)})},function(e,t,n){(function(t){const s=n(15),{constructors:i}=(n(62),n(20)),{readBigIntFromBuffer:a,readBufferFromBigInt:r,sha256:o,bigIntMod:c,modExp:u,generateRandomBytes:l}=n(8),d=n(36);function f(e,n){if(!t.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(n))throw new Error("Changing passwords unsupported")}function g(e){return t.concat([t.alloc(256-e.length),e])}function p(e){return r(e,256,!1)}function h(e,t){const n=t.subtract(e);return!(n.lesser(s(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function m(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=l(256),n=a(e,!1),i=u(s(_),n,b);if(h(i,b)){const e=p(i),r=a(await o(t.concat([e,P])),!1);if(r.greater(s(0)))return[n,e,r]}}})(),O=c(w.subtract(M),b);if(!h(O,b))throw new Error("bad gB");const U=R.multiply(v),T=k.add(U),B=u(O,T,b),[D,x,j,N,F]=await Promise.all([o(p(B)),o(A),o(I),o(r.salt1),o(r.salt2)]),V=await o(t.concat([m(x,j),N,F,E,P,D]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:t.from(E),M1:V})},computeDigest:async function(e,t){try{f(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return p(u(s(e.g),a(await y(e,t),!1),a(e.p,!1)))}}}).call(this,n(12).Buffer)},function(e,t,n){n(21),n(20).constructors;const s=n(49);e.exports=class extends s{constructor(){super(),this._serverAddress=null,this._dcId=0,this._port=null,this._takeoutId=null,this._entities=new Set,this._updateStates={}}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}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}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{serializeBytes:i}=n(20),{inflate:a}=n(43);class r{constructor(e){this.data=e,this.CONSTRUCTOR_ID=812830625,this.classType="constructor"}static async gzipIfSmaller(e,t){if(e&&t.length>512){const e=await new r(t).toBytes();if(e.length{const s=new FileReader;s.onload=e=>{const{result:s}=e.target||{};"string"==typeof s&&t(s),n(new Error("Failed to read blob"))},s.onerror=n,s.readAsDataURL(e)})}async function a(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}},function(e,t,n){(function(t){const s=n(46).default,{i2ab:i,ab2i:a}=n(76),{getWords:r}=n(77);class o{constructor(e){this.setBytes(e)}setBytes(e){e=t.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class c{constructor(e,t){t instanceof o||(t=new o(t)),this._counter=t,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new s(r(e))}update(e){return this.encrypt(e)}encrypt(e){const n=t.from(e);for(let e=0;e{s[e]&&r[e]&&(this._authKeys[e]=new i(t.from(s[e].data),t.from(r[e].data)))})}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey="GramJs-session-"+Date.now()),await this._updateStorage(),this._storageKey}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}async _updateStorage(){if(!this._storageKey)return;const e={mainDcId:this._dcId,keys:{},hashes:{}};Object.keys(this._authKeys).map(t=>{const n=this._authKeys[t];e.keys[t]=n._key,e.hashes[t]=n._hash});try{await this._saveToCache(JSON.stringify(e))}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)}}async _delete(){throw new Error("Not Implemented")}async _fetchFromCache(){throw new Error("Not Implemented")}async _saveToCache(e){throw new Error("Not Implemented")}}}).call(this,n(12).Buffer)},function(e,t,n){e.exports=function e(t,n,s){function i(r,o){if(!n[r]){if(!t[r]){if(a)return a(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[r]={exports:{}};t[r][0].call(u.exports,(function(e){return i(t[r][1][e]||e)}),u,u.exports,e,t,n,s)}return n[r].exports}for(var a=!1,r=0;r=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&a||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r>>6,t[r++]=128|63&n):n<65536?(t[r++]=224|n>>>12,t[r++]=128|n>>>6&63,t[r++]=128|63&n):(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63,t[r++]=128|n>>>6&63,t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n4)u[s++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?u[s++]=65533:i<65536?u[s++]=i:(i-=65536,u[s++]=55296|i>>10&1023,u[s++]=56320|1023&i)}return c(u,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,s){for(var i=65535&e|0,a=e>>>16&65535|0,r=0;0!==n;){n-=r=n>2e3?2e3:n;do{a=a+(i=i+t[s++]|0)|0}while(--r);i%=65521,a%=65521}return i|a<<16|0}},{}],4:[function(e,t,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){"use strict";var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=s,r=i+n;e^=-1;for(var o=i;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,n){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){"use strict";t.exports=function(e,t){var n,s,i,a,r,o,c,u,l,d,f,g,p,h,m,y,b,_,w,v,A,I,P,S,C;n=e.state,s=e.next_in,S=e.input,i=s+(e.avail_in-5),a=e.next_out,C=e.output,r=a-(t-e.avail_out),o=a+(e.avail_out-257),c=n.dmax,u=n.wsize,l=n.whave,d=n.wnext,f=n.window,g=n.hold,p=n.bits,h=n.lencode,m=n.distcode,y=(1<>>=w=_>>>24,p-=w,0==(w=_>>>16&255))C[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=h[(65535&_)+(g&(1<>>=w,p-=w),p<15&&(g+=S[s++]<>>=w=_>>>24,p-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(g&(1<c){e.msg="invalid distance too far back",n.mode=30;break e}if(g>>>=w,p-=w,A>(w=a-r)){if((w=A-w)>l&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(I=0,P=f,0===d){if(I+=u-w,w2;)C[a++]=P[I++],C[a++]=P[I++],C[a++]=P[I++],v-=3;v&&(C[a++]=P[I++],v>1&&(C[a++]=P[I++]))}else{I=a-A;do{C[a++]=C[I++],C[a++]=C[I++],C[a++]=C[I++],v-=3}while(v>2);v&&(C[a++]=C[I++],v>1&&(C[a++]=C[I++]))}break}}break}}while(s>3,g&=(1<<(p-=v<<3))-1,e.next_in=s,e.next_out=a,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function l(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):-2}function d(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,l(e)):-2}function f(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?-2:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,d(e))):-2}function g(e,t){var n,s;return e?(s=new u,e.state=s,s.window=null,0!==(n=f(e,t))&&(e.state=null),n):-2}var p,h,m=!0;function y(e){if(m){var t;for(p=new s.Buf32(512),h=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,p,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,h,0,e.work,{bits:5}),m=!1}e.lencode=p,e.lenbits=9,e.distcode=h,e.distbits=5}function b(e,t,n,i){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((a=r.wsize-r.wnext)>i&&(a=i),s.arraySet(r.window,t,n-i,a,r.wnext),(i-=a)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=a(n.check,D,2,0),h=0,m=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",n.mode=30;break}if(m-=4,R=8+(15&(h>>>=4)),0===n.wbits)n.wbits=R;else if(R>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(D[0]=255&h,D[1]=h>>>8&255,n.check=a(n.check,D,2,0)),h=0,m=0,n.mode=3;case 3:for(;m<32;){if(0===g)break e;g--,h+=u[d++]<>>8&255,D[2]=h>>>16&255,D[3]=h>>>24&255,n.check=a(n.check,D,4,0)),h=0,m=0,n.mode=4;case 4:for(;m<16;){if(0===g)break e;g--,h+=u[d++]<>8),512&n.flags&&(D[0]=255&h,D[1]=h>>>8&255,n.check=a(n.check,D,2,0)),h=0,m=0,n.mode=5;case 5:if(1024&n.flags){for(;m<16;){if(0===g)break e;g--,h+=u[d++]<>>8&255,n.check=a(n.check,D,2,0)),h=0,m=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((v=n.length)>g&&(v=g),v&&(n.head&&(R=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,u,d,v,R)),512&n.flags&&(n.check=a(n.check,u,v,d)),g-=v,d+=v,n.length-=v),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===g)break e;v=0;do{R=u[d+v++],n.head&&R&&n.length<65536&&(n.head.name+=String.fromCharCode(R))}while(R&&v>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;m<32;){if(0===g)break e;g--,h+=u[d++]<>>=7&m,m-=7&m,n.mode=27;break}for(;m<3;){if(0===g)break e;g--,h+=u[d++]<>>=1)){case 0:n.mode=14;break;case 1:if(y(n),n.mode=20,6===t){h>>>=2,m-=2;break e}break;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}h>>>=2,m-=2;break;case 14:for(h>>>=7&m,m-=7&m;m<32;){if(0===g)break e;g--,h+=u[d++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&h,h=0,m=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(v=n.length){if(v>g&&(v=g),v>p&&(v=p),0===v)break e;s.arraySet(l,u,d,v,f),g-=v,d+=v,p-=v,f+=v,n.length-=v;break}n.mode=12;break;case 17:for(;m<14;){if(0===g)break e;g--,h+=u[d++]<>>=5,m-=5,n.ndist=1+(31&h),h>>>=5,m-=5,n.ncode=4+(15&h),h>>>=4,m-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,m-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,U={bits:n.lenbits},O=o(0,n.lens,0,19,n.lencode,0,n.work,U),n.lenbits=U.bits,O){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,C=65535&B,!((P=B>>>24)<=m);){if(0===g)break e;g--,h+=u[d++]<>>=P,m-=P,n.lens[n.have++]=C;else{if(16===C){for(T=P+2;m>>=P,m-=P,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}R=n.lens[n.have-1],v=3+(3&h),h>>>=2,m-=2}else if(17===C){for(T=P+3;m>>=P)),h>>>=3,m-=3}else{for(T=P+7;m>>=P)),h>>>=7,m-=7}if(n.have+v>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;v--;)n.lens[n.have++]=R}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,U={bits:n.lenbits},O=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,U),n.lenbits=U.bits,O){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,U={bits:n.distbits},O=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,U),n.distbits=U.bits,O){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(g>=6&&p>=258){e.next_out=f,e.avail_out=p,e.next_in=d,e.avail_in=g,n.hold=h,n.bits=m,r(e,w),f=e.next_out,l=e.output,p=e.avail_out,d=e.next_in,u=e.input,g=e.avail_in,h=n.hold,m=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;S=(B=n.lencode[h&(1<>>16&255,C=65535&B,!((P=B>>>24)<=m);){if(0===g)break e;g--,h+=u[d++]<>M)])>>>16&255,C=65535&B,!(M+(P=B>>>24)<=m);){if(0===g)break e;g--,h+=u[d++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,n.length=C,0===S){n.mode=26;break}if(32&S){n.back=-1,n.mode=12;break}if(64&S){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&S,n.mode=22;case 22:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;S=(B=n.distcode[h&(1<>>16&255,C=65535&B,!((P=B>>>24)<=m);){if(0===g)break e;g--,h+=u[d++]<>M)])>>>16&255,C=65535&B,!(M+(P=B>>>24)<=m);){if(0===g)break e;g--,h+=u[d++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,64&S){e.msg="invalid distance code",n.mode=30;break}n.offset=C,n.extra=15&S,n.mode=24;case 24:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===p)break e;if(v=w-p,n.offset>v){if((v=n.offset-v)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}v>n.wnext?(v-=n.wnext,A=n.wsize-v):A=n.wnext-v,v>n.length&&(v=n.length),I=n.window}else I=l,A=f-n.offset,v=n.length;v>p&&(v=p),p-=v,n.length-=v;do{l[f++]=I[A++]}while(--v);0===n.length&&(n.mode=21);break;case 26:if(0===p)break e;l[f++]=n.length,p--,n.mode=21;break;case 27:if(n.wrap){for(;m<32;){if(0===g)break e;g--,h|=u[d++]<=1&&0===D[C];C--);if(M>C&&(M=C),0===C)return u[l++]=20971520,u[l++]=20971520,f.bits=1,0;for(S=1;S0&&(0===e||1!==C))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+D[I];for(P=0;P852||2===e&&O>592)return 1;for(;;){_=I-E,d[P]b?(w=j[N+d[P]],v=T[B+d[P]]):(w=96,v=0),g=1<>E)+(p-=g)]=_<<24|w<<16|v|0}while(0!==p);for(g=1<>=1;if(0!==g?(U&=g-1,U+=g):U=0,P++,0==--D[I]){if(I===C)break;I=t[n+d[P]]}if(I>M&&(U&m)!==h){for(0===E&&(E=M),y+=S,R=1<<(k=I-E);k+E852||2===e&&O>592)return 1;u[h=U&m]=M<<24|k<<16|y-l|0}}return 0!==U&&(u[y+U]=I-E<<24|64<<16|0),f.bits=M,0}},{"../utils/common":1}],10:[function(e,t,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){"use strict";var s=e("./zlib/inflate"),i=e("./utils/common"),a=e("./utils/strings"),r=e("./zlib/constants"),o=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),l=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(o[n]);if(this.header=new u,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(o[n])}function f(e,t){var n=new d(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}d.prototype.push=function(e,t){var n,o,c,u,d,f=this.strm,g=this.options.chunkSize,p=this.options.dictionary,h=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?f.input=a.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?f.input=new Uint8Array(e):f.input=e,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new i.Buf8(g),f.next_out=0,f.avail_out=g),(n=s.inflate(f,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&p&&(n=s.inflateSetDictionary(this.strm,p)),n===r.Z_BUF_ERROR&&!0===h&&(n=r.Z_OK,h=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),this.ended=!0,!1;f.next_out&&(0!==f.avail_out&&n!==r.Z_STREAM_END&&(0!==f.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=a.utf8border(f.output,f.next_out),u=f.next_out-c,d=a.buf2string(f.output,c),f.next_out=u,f.avail_out=g-u,u&&i.arraySet(f.output,f.output,c,u,0),this.onData(d)):this.onData(i.shrinkBuf(f.output,f.next_out)))),0===f.avail_in&&0===f.avail_out&&(h=!0)}while((f.avail_in>0||0===f.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),f.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=d,n.inflate=f,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.ungzip=f},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(t){const n=e=>e.replace(/(?:^|_)([a-z])/g,(e,t)=>t.toUpperCase()).replace(/_/g,""),s=e=>e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_","")),i=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),a=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let r=null;function o(e){r||(r=function(){let e;const t=[];for(let n=0;n<256;n++){e=n;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0}const c=(e,i)=>{const a=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!a)throw new Error("Cannot parse TLObject "+e);const r=l(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),c={name:a[1],constructorId:parseInt(a[2],16),argsConfig:{},subclassOfId:o(a[3]),result:a[3],isFunction:i,namespace:null};if(!c.constructorId){let e,n="";e=Object.values(c.argsConfig).length?" "+Object.keys(c.argsConfig).map(e=>e.toString()).join(" "):"";const s=`${c.name}${n}${e} = ${c.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===c.name&&c.name,c.constructorId=o(t.from(s,"utf8"))}for(const[e,t,n]of r)void 0===e&&(c.argsConfig[s(t)]=u(t,n));return c.name.includes(".")&&([c.namespace,c.name]=c.name.split(/\.(.+)/)),c.name=n(c.name),c};function u(e,t){const n={isVector:!1,isFlag:!1,skipConstructorId:!1,flagIndex:-1,flagIndicator:!0,type:null,useVectorId:null};e="self"===e?"is_self":e;if("#"!==t){n.flagIndicator=!1,n.type=t.replace(/^!+/,"");const e=n.type.match(/flags.(\d+)\?([\w<>.]+)/);e&&(n.isFlag=!0,n.flagIndex=Number(e[1]),[,,n.type]=e);const s=n.type.match(/[Vv]ector<([\w\d.]+)>/);s&&(n.isVector=!0,n.useVectorId="V"===n.type.charAt(0),[,n.type]=s),/^[a-z]$/.test(n.type.split(".").pop().charAt(0))&&(n.skipConstructorId=!0)}return n}const l=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),l(e,t,n)),n};e.exports={findAll:l,parseTl:function*(e,t,n=[],s=i){(n||[]).reduce((e,t)=>({...e,[t.name]:t}),{});const r=[],o={},u={},l=e;let d=!1;for(let e of l.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;d="functions"===e}else try{const t=c(e,d);if(s.has(t.constructorId))continue;r.push(t),t.isFunction||(u[t.result]||(u[t.result]=[]),o[t.name]=t,u[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of r)if(a.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of r)yield e},buildArgConfig:u,fromLine:c,CORE_TYPES:i,serializeDate:function(e){if(!e)return t.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const n=t.alloc(4);return n.writeInt32LE(e,0),n}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof t)){if("string"!=typeof e)throw Error("Bytes or str expected, not "+e.constructor.name);e=t.from(e)}const n=[];let s;return e.length<254?(s=(e.length+1)%4,0!==s&&(s=4-s),n.push(t.from([e.length])),n.push(e)):(s=e.length%4,0!==s&&(s=4-s),n.push(t.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),n.push(e)),n.push(t.alloc(s).fill(0)),t.concat(n)},snakeToCamelCase:n,variableSnakeToCamelCase:s}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"CTR",(function(){return y})),n.d(t,"IGE",(function(){return m}));var s=new Uint8Array(256),i=new Uint8Array(256),a=new Uint32Array(256),r=new Uint32Array(256),o=new Uint32Array(256),c=new Uint32Array(256),u=new Uint32Array(256),l=new Uint32Array(256),d=new Uint32Array(256),f=new Uint32Array(256);function g(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(var t=e.length%4;t<=4;t++)e+="\0x00";var n=new Uint32Array(e.length/4);for(t=0;t>7),m[h[_]^_]=_;for(;!s[y];y^=e||1)n=(n=b^b<<1^b<<2^b<<3^b<<4)>>8^255&n^99,s[y]=n,i[n]=y,p=16843009*h[t=h[e=h[y]]]^65537*t^257*e^16843008*y,g=257*h[n]^16843008*n,a[y]=g=g<<24^g>>>8,r[y]=g=g<<24^g>>>8,o[y]=g=g<<24^g>>>8,c[y]=g=g<<24^g>>>8,u[n]=p=p<<24^p>>>8,l[n]=p=p<<24^p>>>8,d[n]=p=p<<24^p>>>8,f[n]=p=p<<24^p>>>8,b=m[b]||1}();var h=function(){function e(e){var t=g(e);if(4!==t.length&&6!==t.length&&8!==t.length)throw new Error("Invalid key size");this.encKey=new Uint32Array(4*t.length+28),this.decKey=new Uint32Array(4*t.length+28),this.encKey.set(t);for(var n,i=1,a=t.length;a<4*t.length+28;a++)n=this.encKey[a-1],(a%t.length==0||8===t.length&&a%t.length==4)&&(n=s[n>>>24]<<24^s[n>>16&255]<<16^s[n>>8&255]<<8^s[255&n],a%t.length==0&&(n=n<<8^n>>>24^i<<24,i=i<<1^283*(i>>7))),this.encKey[a]=this.encKey[a-t.length]^n;for(var r=0;a;r++,a--)n=this.encKey[3&r?a:a-4],this.decKey[r]=a<=4||r<4?n:u[s[n>>>24]]^l[s[n>>16&255]]^d[s[n>>8&255]]^f[s[255&n]]}return e.prototype.encrypt=function(e){for(var t,n,i,u=g(e),l=new Uint32Array(4),d=u[0]^this.encKey[0],f=u[1]^this.encKey[1],p=u[2]^this.encKey[2],h=u[3]^this.encKey[3],m=this.encKey.length/4-2,y=4,b=0;b>>24]^r[f>>16&255]^o[p>>8&255]^c[255&h]^this.encKey[y],n=a[f>>>24]^r[p>>16&255]^o[h>>8&255]^c[255&d]^this.encKey[y+1],i=a[p>>>24]^r[h>>16&255]^o[d>>8&255]^c[255&f]^this.encKey[y+2],h=a[h>>>24]^r[d>>16&255]^o[f>>8&255]^c[255&p]^this.encKey[y+3],d=t,f=n,p=i,y+=4;for(b=0;b<4;b++)l[b]=s[d>>>24]<<24^s[f>>16&255]<<16^s[p>>8&255]<<8^s[255&h]^this.encKey[y++],t=d,d=f,f=p,p=h,h=t;return l},e.prototype.decrypt=function(e){for(var t,n,s,a=g(e),r=new Uint32Array(4),o=a[0]^this.decKey[0],c=a[3]^this.decKey[1],p=a[2]^this.decKey[2],h=a[1]^this.decKey[3],m=this.decKey.length/4-2,y=4,b=0;b>>24]^l[c>>16&255]^d[p>>8&255]^f[255&h]^this.decKey[y],n=u[c>>>24]^l[p>>16&255]^d[h>>8&255]^f[255&o]^this.decKey[y+1],s=u[p>>>24]^l[h>>16&255]^d[o>>8&255]^f[255&c]^this.decKey[y+2],h=u[h>>>24]^l[o>>16&255]^d[c>>8&255]^f[255&p]^this.decKey[y+3],o=t,c=n,p=s,y+=4;for(b=0;b<4;b++)r[3&-b]=i[o>>>24]<<24^i[c>>16&255]<<16^i[p>>8&255]<<8^i[255&h]^this.decKey[y++],t=o,o=c,c=p,p=h,h=t;return r},e}(),m=function(){function e(e,t,n){void 0===n&&(n=16),this.key=g(e),this.iv=g(t),this.cipher=new h(e),this.blockSize=n/4}return e.prototype.encrypt=function(e,t){for(var n=g(e),s=t||new Uint32Array(n.length),i=this.iv.subarray(this.blockSize,this.iv.length),a=this.iv.subarray(0,this.blockSize),r=new Uint32Array(this.blockSize),o=0;o=this.blockSize&&this.incrementCounter(),i&&(a-=i,i=0)}return this.offset=(this.offset+n.length%4)%4,s},e.prototype.decrypt=function(e,t){return this.encrypt(e,t)},e.prototype.incrementCounter=function(){for(var e=this.counter.length-1;e>=0&&!(++this.counter[e]<4294967295);e--);},e}();t.default=h},function(e,t,n){(function(t){let n=null;class s{constructor(e){n||(n=e||"debug"),this.isBrowser=void 0===t||"renderer"===t.type||!0===t.browser||t.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"",warn:"",info:"",debug:"",error:"",end:""},this.messageFormat="[%t] [%l] - [%m]"}canSend(e){return s.levels.indexOf(n)>=s.levels.indexOf(e)}warn(e){this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}static setLevel(e){n=e}_log(e,t,s){n&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(t,e),s):console.log(s+this.format(t,e)+this.colors.end))}}var i,a,r;r=["error","warn","info","debug"],(a="levels")in(i=s)?Object.defineProperty(i,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[a]=r,e.exports=s}).call(this,n(82))},function(e,t,n){const{RPCError:s,InvalidDCError:i,FloodError:a,BadRequestError:r}=n(37);class o extends i{constructor(e){const t=Number(e.capture||0);super("The user whose identity is being used to execute queries is associated with DC "+t+s._fmtRequest(e.request)),this.message="The user whose identity is being used to execute queries is associated with DC "+t+s._fmtRequest(e.request),this.newDc=t}}class c extends i{constructor(e){const t=Number(e.capture||0);super("The phone number a user is trying to use for authorization is associated with DC "+t+s._fmtRequest(e.request)),this.message="The phone number a user is trying to use for authorization is associated with DC "+t+s._fmtRequest(e.request),this.newDc=t}}class u extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat`+s._fmtRequest(e.request)),this.message=`A wait of ${t} seconds is required before sending another message in this chat`+s._fmtRequest(e.request),this.seconds=t}}class l extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required`+s._fmtRequest(e.request)),this.message=`A wait of ${t} seconds is required`+s._fmtRequest(e.request),this.seconds=t}}class d extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers`+s._fmtRequest(e.request)),this.message=`A wait of ${t} seconds is required in the test servers`+s._fmtRequest(e.request),this.seconds=t}}class f extends i{constructor(e){const t=Number(e.capture||0);super("The file to be accessed is currently stored in DC "+t+s._fmtRequest(e.request)),this.message="The file to be accessed is currently stored in DC "+t+s._fmtRequest(e.request),this.newDc=t}}class g extends i{constructor(e){const t=Number(e.capture||0);super("The source IP address is associated with DC "+t+s._fmtRequest(e.request)),this.message="The source IP address is associated with DC "+t+s._fmtRequest(e.request),this.newDc=t}}class p extends r{constructor(e){const t=Number(e.capture||0);super("Email unconfirmed, the length of the code must be "+t+s._fmtRequest(e.request)),this.message="Email unconfirmed, the length of the code must be "+t+s._fmtRequest(e.request),this.codeLength=t}}const h=[[/FILE_MIGRATE_(\d+)/,f],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,d],[/FLOOD_WAIT_(\d+)/,l],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,u],[/USER_MIGRATE_(\d+)/,o],[/NETWORK_MIGRATE_(\d+)/,g],[/EMAIL_UNCONFIRMED_(\d+)/,p]];e.exports={rpcErrorRe:h,FileMigrateError:f,FloodTestPhoneWaitError:d,FloodWaitError:l,PhoneMigrateError:c,SlowModeWaitError:u,UserMigrateError:o,NetworkMigrateError:g,EmailUnconfirmedError:p}},function(e,t){e.exports=class{constructor(){}setDC(e,t,n){throw new Error("Not implemented")}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")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},function(e,t,n){(function(t){e.exports=class{constructor(e){this._stream=e}write(e){this._stream=t.concat([this._stream,e])}getValue(){return this._stream}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(38),i=n(52),a=n(39),r=n(31),o={[i.CONSTRUCTOR_ID]:i,[r.CONSTRUCTOR_ID]:r,[a.CONSTRUCTOR_ID]:a};e.exports={TLMessage:s,RPCResult:i,MessageContainer:a,GZIPPacked:r,coreObjects:o}},function(e,t,n){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{RpcError:i}=n(20).constructors,a=n(31);class r{constructor(e,t,n){this.CONSTRUCTOR_ID=4082920705,this.reqMsgId=e,this.body=t,this.error=n,this.classType="constructor"}static async fromReader(e){const t=e.readLong(),n=e.readInt(!1);return n===i.CONSTRUCTOR_ID?new r(t,null,i.fromReader(e)):n===a.CONSTRUCTOR_ID?new r(t,(await a.fromReader(e)).data):(e.seek(-4),new r(t,e.read(),null))}}s(r,"CONSTRUCTOR_ID",4082920705),s(r,"classType","constructor"),e.exports=r},function(e,t,n){const s=n(6),i={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)i[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))i[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:121,tlobjects:i}},function(e,t,n){(function(t){const s=new(0,n(83).Mutex),i=n(85).w3cwebsocket,a=new Error("WebSocket was closed");e.exports=class{constructor(){this.client=null,this.closed=!0}async readExactly(e){let n=t.alloc(0);for(;;){const s=await this.read(e);if(n=t.concat([n,s]),!(e-=s.length))return n}}async read(e){if(this.closed)throw a;if(await this.canRead,this.closed)throw a;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 a;const e=this.stream;return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}async connect(e,n){return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),this.closed=!1,this.website=this.getWebSocketLink(n,e),this.client=new i(this.website,"binary"),new Promise((e,t)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{t(e)},this.client.onclose=()=>{this.resolveRead(!1),this.closed=!0},self.addEventListener("offline",async()=>{await this.close(),this.resolveRead(!1)})})}write(e){if(this.closed)throw a;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}async receive(){this.client.onmessage=async e=>{const n=await s.acquire();try{const s=e.data instanceof ArrayBuffer?t.from(e.data):t.from(await new Response(e.data).arrayBuffer());this.stream=t.concat([this.stream,s]),this.resolveRead(!0)}finally{n()}}}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const s=n(39),i=n(38),a=n(50);e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise(e=>{this.setReady=e}),this._log=t}values(){return this._queue}append(e){this._queue.push(e),this.setReady(!0),e&&(this._pendingStates.push(e),e.promise.catch(()=>{}).finally(()=>{this._pendingStates=this._pendingStates.filter(t=>t!==e)}))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise(e=>{this.setReady=e}),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,n=new a(t.alloc(0));const r=[];let o=0;for(;this._queue.length&&r.length<=s.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=s.MAXIMUM_SIZE){let t;e.after&&(t=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(n,e.data,"request"===e.request.classType,t),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),r.push(e)}else{if(r.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),o=0}}if(!r.length)return null;if(r.length>1){const i=t.alloc(8);i.writeUInt32LE(s.CONSTRUCTOR_ID,0),i.writeInt32LE(r.length,4),e=t.concat([i,n.getValue()]),n=new a(t.alloc(0));const o=await this._state.writeDataAsMessage(n,e,!1);for(const e of r)e.containerId=o}return e=n.getValue(),{batch:r,data:e}}rejectAll(){this._pendingStates.forEach(e=>{e.reject(new Error("Disconnect"))})}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(){this._queue=[],this.canGet=new Promise(e=>{this.resolveGet=e}),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise(e=>{this.resolvePush=e})}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise(e=>{this.resolveGet=e}),e}}},function(e,t,n){const s=n(58),i=n(59),a=n(8),r=n(32),o=n(61),c=n(52),u=n(39),l=n(31),d=n(90),{MsgsAck:f,upload:g,MsgsStateInfo:p,Pong:h}=n(20).constructors,m=n(55),y=n(25),{UpdateConnectionState:b}=n(40),{BadMessageError:_}=n(23),{BadServerSalt:w,BadMsgNotification:v,MsgDetailedInfo:A,MsgNewDetailedInfo:I,NewSessionCreated:P,FutureSalts:S,MsgsStateReq:C,MsgResendReq:M,MsgsAllInfo:k}=n(20).constructors,{SecurityError:E}=n(23),{InvalidBufferError:R}=n(23),{LogOut:O}=n(20).requests.auth,{RPCMessageToError:U}=n(27),{TypeNotFoundError:T}=n(23);class B{constructor(e,t){const n={...B.DEFAULT_OPTIONS,...t};this._connection=null,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=null,this._recv_loop_handle=null,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[u.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[l.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[w.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[I.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[f.CONSTRUCTOR_ID]:this._handleAck.bind(this),[S.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[C.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this._connection=e;for(let e=0;e>2;if(n<127){const e=t.alloc(1);e.writeUInt8(n,0),n=e}else n=t.concat([t.from("7f","hex"),i(o(n),3)]);return t.concat([n,e])}async readPacket(e){let n=(await e.read(1))[0];return n>=127&&(n=t.concat([await e.read(3),t.alloc(1)]).readInt32LE(0)),await e.read(n<<2)}}s(c,"tag",t.from("ef","hex")),s(c,"obfuscateTag",t.from("efefefef","hex"));e.exports={ConnectionTCPAbridged:class extends a{constructor(...e){super(...e),s(this,"PacketCodecClass",c)}},AbridgedPacketCodec:c}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(8),{ObfuscatedConnection:a}=n(41),{AbridgedPacketCodec:r}=n(63),o=n(93);class c{constructor(e){s(this,"header",null),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const n=[t.from("50567247","hex"),t.from("474554","hex"),t.from("504f5354","hex"),t.from("eeeeeeee","hex")];let s;for(;;)if(s=i(64),239!==s[0]&&!s.slice(4,8).equals(t.alloc(4))){let e=!0;for(const t of n)if(t.equals(s.slice(0,4))){e=!1;break}if(e)break}s=s.toJSON().data;const a=t.from(s.slice(8,56)).reverse(),r=t.from(s.slice(8,40)),c=t.from(s.slice(40,56)),u=t.from(a.slice(0,32)),l=t.from(a.slice(32,48)),d=new o(r,c),f=new o(u,l);return s=t.concat([t.from(s.slice(0,56)),e.obfuscateTag,t.from(s.slice(60))]),s=t.concat([t.from(s.slice(0,56)),t.from(d.encrypt(s).slice(56,64)),t.from(s.slice(64))]),{random:s,encryptor:d,decryptor:f}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends a{constructor(...e){super(...e),s(this,"ObfuscatedIO",c),s(this,"PacketCodecClass",r)}}}}).call(this,n(12).Buffer)},function(e,t){},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(s||(s={}));const i=-1,a="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(s||(s={}))},function(e,t){},function(e,t){},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r}));var s=n(1),i=n(0),a=n(2);async function r({chatId:t,accessHash:n,messageId:r,data:o}){const c=await Object(s.g)(new i.Api.messages.GetBotCallbackAnswer({peer:Object(a.i)(t,n),msgId:r,data:e.from(o)}));if(c)return c}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";t.byteLength=function(e){var t=u(e),n=t[0],s=t[1];return 3*(n+s)/4-s},t.toByteArray=function(e){var t,n,s=u(e),r=s[0],o=s[1],c=new a(function(e,t,n){return 3*(t+n)/4-n}(0,r,o)),l=0,d=o>0?r-4:r;for(n=0;n>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===o&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[l++]=255&t);1===o&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],r=0,o=n-i;ro?o:r+16383));1===i?(t=e[n-1],a.push(s[t>>2]+s[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=r.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var i,a,r=[],o=t;o>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,s,i){var a,r,o=8*i-s-1,c=(1<>1,l=-7,d=n?i-1:0,f=n?-1:1,g=e[t+d];for(d+=f,a=g&(1<<-l)-1,g>>=-l,l+=o;l>0;a=256*a+e[t+d],d+=f,l-=8);for(r=a&(1<<-l)-1,a>>=-l,l+=s;l>0;r=256*r+e[t+d],d+=f,l-=8);if(0===a)a=1-u;else{if(a===c)return r?NaN:1/0*(g?-1:1);r+=Math.pow(2,s),a-=u}return(g?-1:1)*r*Math.pow(2,a-s)},t.write=function(e,t,n,s,i,a){var r,o,c,u=8*a-i-1,l=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=s?0:a-1,p=s?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,r=l):(r=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-r))<1&&(r--,c*=2),(t+=r+d>=1?f/c:f*Math.pow(2,1-d))*c>=2&&(r++,c/=2),r+d>=l?(o=0,r=l):r+d>=1?(o=(t*c-1)*Math.pow(2,i),r+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,i),r=0));i>=8;e[n+g]=255&o,g+=p,o/=256,i-=8);for(r=r<0;e[n+g]=255&r,g+=p,r/=256,u-=8);e[n+g-p]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=255&i}return t.buffer}function i(e){return e.buffer}function a(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;e 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#23ab23d2 flags:# id:InputDocument ttl_seconds:flags.0?int = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#f4e096c3 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#27d69997 flags:# big:flags.0?true peer:InputPeer volume_id:long local_id:int = InputFileLocation;\ninputStickerSetThumb#dbaeae9 stickerset:InputStickerSet volume_id:long local_id: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 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#69d3ab26 flags:# has_video:flags.0?true photo_id:long photo_small:FileLocation photo_big:FileLocation 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 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 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#1b7c9db3 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:ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int = ChatFull;\nchannelFull#f0e6672a 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: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 = 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#d20b9f3c flags:# has_video:flags.0?true photo_small:FileLocation photo_big:FileLocation dc_id:int = ChatPhoto;\nmessageEmpty#83e5de54 id:int = Message;\nmessage#58ae39c9 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 = Message;\nmessageService#286fa604 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 = 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;\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#77bfb61b type:string location:FileLocation w:int h:int size:int = PhotoSize;\nphotoCachedSize#e9a734fa type:string location:FileLocation w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#5aa86a51 type:string location:FileLocation 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 geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#e1746d0a text:string = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\nuserFull#edf17c12 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 = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#9a65ea1f chat_id:int user_id:int action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#12b9417b user_id:int phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#54826690 flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#e73547e1 flags:# query_id:long user_id:int peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#42f88f2c poll_id:long user_id:int options:Vector = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelParticipant#65d2b464 flags:# channel_id:int date:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant qts:int = Update;\nupdateChannelMessageForwards#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#ff2abe9f flags:# channel_id:int top_msg_id:flags.0?int user_id:int action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#2296d2c8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShortChatMessage#402d5dbb flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#11f1331c flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#13d6dd27 id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteEmpty#69df3769 = ExportedChatInvite;\nchatInviteExported#fc2e05bc link:string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#eeb46f27 flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumb:flags.4?PhotoSize thumb_dc_id:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#1c0facaf flags:# left:flags.0?true user_id:int kicked_by:int date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#c3c6796b user_id:int = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#f56ee2a8 count:int participants:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#d0d9b163 participant:ChannelParticipant users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#2e0709a5 hash:int gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#58fffcd0 pos:int user_id:int score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#c30aa358 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#3f56aea3 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#500911e1 flags:# date:int bot_id:int invoice:Invoice provider_id:int info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsAndroidPay#ca05d50e payment_token:DataJSON google_transaction_id:string = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#cac943f2 hash:long bot_id:int domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#5108d648 hash:int sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#badcc1a3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfileLocationToBeDeprecated#bc7fc6cd volume_id:long local_id:int = FileLocation;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\n// Some unused classes were removed below this line\nvideoSize#e831c556 flags:# type:string location:FileLocation w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nmessages.discussionMessage#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector = Bool;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#d4982db5 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#df7534c peer:InputPeer = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = channels.ChannelParticipants;\nchannels.getParticipant#546dd7a6 channel:InputChannel user_id:InputUser = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#72796912 channel:InputChannel user_id:InputUser banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#99f09745 msg_id:int = payments.PaymentForm;\npayments.getPaymentReceipt#a092a980 msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#770a8e74 flags:# save:flags.0?true msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#2b8879b3 flags:# msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 121\n"},function(e,t){e.exports="resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n"},function(e,t,n){const s=n(47),{sleep:i}=n(8),a=n(27),r=n(30),o=n(8),{BinaryWriter:c}=n(33),u=n(21),l=n(49),d=n(88),{LAYER:f}=n(53),{constructors:g,requests:p}=n(20),h=n(57),{UpdateConnectionState:m}=n(40),{ConnectionTCPObfuscated:y}=n(64),{authFlow:b,checkAuthorization:_}=n(94),{downloadFile:w}=n(95),{uploadFile:v}=n(96),{updateTwoFaSettings:A}=n(97),I=["w","y","d","x","c","m","b","a","s"];class P{constructor(e,t,n,i=P.DEFAULT_OPTIONS){if(void 0===t||void 0===n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const a={...P.DEFAULT_OPTIONS,...i};if(this.apiId=t,this.apiHash=n,this._useIPV6=a.useIPV6,"string"==typeof a.baseLogger?this._log=new s:this._log=a.baseLogger,"string"!=typeof e&&e){if(!(e instanceof l))throw new Error("The given session must be str or a session instance")}else try{throw new Error("not implemented")}catch(t){e=new r}this.floodSleepLimit=a.floodSleepLimit,this._eventBuilders=[],this._phoneCodeHash={},this.session=e,this.apiId=parseInt(t),this.apiHash=n,this._requestRetries=a.requestRetries,this._connectionRetries=a.connectionRetries,this._retryDelay=a.retryDelay||0,a.proxy&&this._log.warn("proxies are not supported"),this._proxy=a.proxy,this._timeout=a.timeout,this._autoReconnect=a.autoReconnect,this._connection=a.connection,this._floodWaitedRequests={},this._initWith=e=>new p.InvokeWithLayer({layer:f,query:new p.InitConnection({apiId:this.apiId,deviceModel:a.deviceModel||d.type().toString()||"Unknown",systemVersion:a.systemVersion||d.release().toString()||"1.0",appVersion:a.appVersion||"1.0",langCode:a.langCode,langPack:"",systemLangCode:a.systemLangCode,query:e,proxy:null})}),this._args=a,this._config=null,this.phoneCodeHashes=[],this._borrowedSenderPromises={},this._additionalDcsDisabled=a.additionalDcsDisabled}async connect(){await this._initSession(),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});const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e),this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new p.help.GetConfig({}))),this._updateLoop()}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"venus.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;this.isConnected();){await o.sleep(3e3);try{await E(()=>k(this._sender.send(new p.Ping({pingId:o.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)})),1500),3,100)}catch(e){return await this.disconnect(),void this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new p.updates.GetState)}catch(e){}}}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._borrowedSenderPromises).map(e=>e.then(e=>{if(e)return e.disconnect()}))),this._borrowedSenderPromises={}}async destroy(){await this.disconnect(),this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info("Reconnecting to new data center "+e);const t=u.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(null),this.session.setAuthKey(null),await this.disconnect(),this.connect()}async _authKeyCallback(e,t){this.session.setAuthKey(e,t)}_cleanupBorrowedSender(e){delete this._borrowedSenderPromises[e]}async _borrowExportedSender(e){if(this._additionalDcsDisabled)return;let t=this._borrowedSenderPromises[e];return t||(t=this._createExportedSender(e),this._borrowedSenderPromises[e]=t,t.then(t=>{t||delete this._borrowedSenderPromises[e]})),t}async _createExportedSender(e){const t=u.getDC(e),n=new 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._cleanupBorrowedSender.bind(this)});for(let s=0;s<5;s++)try{if(await n.connect(new this._connection(t.ipAddress,t.port,e,this._log)),this.session.dcId!==e){this._log.info("Exporting authorization for data center "+t.ipAddress);const s=await this.invoke(new p.auth.ExportAuthorization({dcId:e})),i=this._initWith(new p.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await n.send(i)}return n.dcId=e,n}catch(e){await n.disconnect()}return null}async downloadFile(e,t={}){return w(this,e,t)}async downloadMedia(e,t){let n,s;if(e instanceof g.Message?(n=e.date,s=e.media):(n=(new Date).getTime(),s=e),"string"==typeof s)throw new Error("not implemented");return s instanceof g.MessageMediaWebPage&&s.webpage instanceof g.WebPage&&(s=s.webpage.document||s.webpage.photo),s instanceof g.MessageMediaPhoto||s instanceof g.Photo?this._downloadPhoto(s,t):s instanceof g.MessageMediaDocument||s instanceof g.Document?this._downloadDocument(s,t):s instanceof g.MessageMediaContact?this._downloadContact(s,t):s instanceof g.WebDocument||s instanceof g.WebDocumentNoProxy?this._downloadWebDocument(s,t):void 0}async downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,i,a;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo)return e.chatPhoto?this._downloadPhoto(e.chatPhoto,{sizeType:n}):null;s=e.photo}else s=e;if(!(s instanceof g.UserProfilePhoto||s instanceof g.ChatPhoto))return null;{i=s.dcId;const n=t?s.photoBig:s.photoSmall;a=new g.InputPeerPhotoFileLocation({peer:u.getInputPeer(e),localId:n.localId,volumeId:n.volumeId,big:t})}try{return this.downloadFile(a,{dcId:i})}catch(e){throw e}}async downloadStickerSetThumb(e){if(!e.thumb||!e.thumb.location)return;const{location:t}=e.thumb;return this.downloadFile(new g.InputStickerSetThumb({stickerset:new g.InputStickerSetID({id:e.id,accessHash:e.accessHash}),localId:t.localId,volumeId:t.volumeId}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return null;let n;for(let s=I.indexOf(t);se.type===I[s]),n)return n;return null}_downloadCachedPhotoSize(e){let t;return t=e instanceof g.PhotoStrippedSize?u.strippedPhotoToJpg(e.bytes):e.bytes,t}async _downloadPhoto(e,t){if(e instanceof g.MessageMediaPhoto&&(e=e.photo),!(e instanceof g.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof g.PhotoSizeEmpty?void 0:n instanceof g.PhotoCachedSize||n instanceof g.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new g.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}async _downloadDocument(e,t){if(e instanceof g.MessageMediaDocument&&(e=e.document),!(e instanceof g.Document))return;let n=null;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):null,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof g.PhotoCachedSize||n instanceof g.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new g.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}_downloadWebDocument(e,t){throw new Error("not implemented")}async invoke(e){if("request"!==e.classType)throw new Error("You can only invoke MTProtoRequests");this._lastRequest=(new Date).getTime();let t=0;for(t=0;tPromise.reject(new Error("TIMEOUT")))])}async function E(e,t,n){for(let s=0;s1)for(var n=1;n0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}();t.default=s},function(e,t,n){(function(t){var s=function(){return this||void 0===t?this:t}(),i=s.WebSocket||s.MozWebSocket,a=n(86);function r(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(r,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?r:null,version:a}}).call(this,n(44))},function(e,t,n){e.exports=n(87).version},function(e){e.exports=JSON.parse('{"_args":[["websocket@1.0.30","/Users/alexander/dev/telegram-t"]],"_from":"websocket@1.0.30","_id":"websocket@1.0.30","_inBundle":false,"_integrity":"sha512-aO6klgaTdSMkhfl5VVJzD5fm+Srhh5jLYbS15+OiI1sN6h/RU/XW6WN9J1uVIpUKNmsTvT3Hs35XAFjn9NMfOw==","_location":"/websocket","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"websocket@1.0.30","name":"websocket","escapedName":"websocket","rawSpec":"1.0.30","saveSpec":null,"fetchSpec":"1.0.30"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/websocket/-/websocket-1.0.30.tgz","_spec":"1.0.30","_where":"/Users/alexander/dev/telegram-t","author":{"name":"Brian McKelvey","email":"theturtle32@gmail.com","url":"https://github.com/theturtle32"},"browser":"lib/browser.js","bugs":{"url":"https://github.com/theturtle32/WebSocket-Node/issues"},"config":{"verbose":false},"contributors":[{"name":"Iñaki Baz Castillo","email":"ibc@aliax.net","url":"http://dev.sipdoc.net"}],"dependencies":{"debug":"^2.2.0","nan":"^2.14.0","typedarray-to-buffer":"^3.1.5","yaeti":"^0.0.6"},"description":"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.","devDependencies":{"buffer-equal":"^1.0.0","faucet":"^0.0.1","gulp":"^4.0.2","gulp-jshint":"^2.0.4","jshint":"^2.0.0","jshint-stylish":"^2.2.1","tape":"^4.9.1"},"directories":{"lib":"./lib"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/theturtle32/WebSocket-Node","keywords":["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],"license":"Apache-2.0","main":"index","name":"websocket","repository":{"type":"git","url":"git+https://github.com/theturtle32/WebSocket-Node.git"},"scripts":{"gulp":"gulp","install":"(node-gyp rebuild 2> builderror.log) || (exit 0)","test":"faucet test/unit"},"version":"1.0.30"}')},function(e,t){t.endianness=function(){return"LE"},t.hostname=function(){return"undefined"!=typeof location?location.hostname:""},t.loadavg=function(){return[]},t.uptime=function(){return 0},t.freemem=function(){return Number.MAX_VALUE},t.totalmem=function(){return Number.MAX_VALUE},t.cpus=function(){return[]},t.type=function(){return"Browser"},t.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},t.networkInterfaces=t.getNetworkInterfaces=function(){return{}},t.arch=function(){return"javascript"},t.platform=function(){return"browser"},t.tmpdir=t.tmpDir=function(){return"/tmp"},t.EOL="\n",t.homedir=function(){return"/"}},function(e,t,n){(function(t){const s=n(15),{readBigIntFromBuffer:i,readBufferFromBigInt:a,getByteArray:r,sha1:o,generateRandomBytes:c,modExp:u}=n(8),l=[{fingerprint:[40,85,94,156,117,240,61,22,65,244,169,2,33,107,232,108,2,43,180,195],n:s("24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407"),e:65537},{fingerprint:[140,171,9,34,146,246,166,50,10,170,229,247,155,114,28,177,29,106,153,154],n:s("25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783"),e:65537},{fingerprint:[243,218,109,239,16,202,176,78,167,8,255,209,120,234,205,112,111,42,91,176],n:s("22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977"),e:65537},{fingerprint:[128,80,214,72,77,244,98,7,201,250,37,244,227,51,96,199,182,37,224,113],n:s("24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351"),e:65537}],d={};l.forEach(({fingerprint:e,...t})=>{d[i(e.slice(-8),!0,!0)]=t}),e.exports={encrypt:async function(e,n){const r=d[e];if(!r)return;const l=c(235-n.length),f=t.concat([await o(n),n,l]),g=i(f,!1),p=u(g,s(r.e),r.n);return a(p,256,!1)}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(e,t=null){this.containerId=null,this.msgId=null,this.request=e,this.data=e.getBytes(),this.after=t,this.result=null,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}},function(e,t,n){const{Connection:s}=n(41),{ConnectionTCPFull:i}=n(92),{ConnectionTCPAbridged:a}=n(63),{ConnectionTCPObfuscated:r}=n(64);e.exports={Connection:s,ConnectionTCPFull:i,ConnectionTCPAbridged:a,ConnectionTCPObfuscated:r}},function(e,t){},function(e,t,n){(function(t){const s=n(36);e.exports=class{constructor(e,n){if(!t.isBuffer(e)||!t.isBuffer(n)||16!==n.length)throw new Error("Key and iv need to be a buffer");this.cipher=s.createCipheriv("AES-256-CTR",e,n)}encrypt(e){return t.from(this.cipher.update(e))}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"authFlow",(function(){return u})),n.d(t,"checkAuthorization",(function(){return l}));var s=n(6),i=n.n(s),a=n(21),r=n.n(a),o=n(8),c=n(29);async function u(e,t,n){const s="phoneNumber"in n?await d(e,t,n):await async function(e,t,n){const{apiId:s,apiHash:a}=t,{botAuthToken:r}=n,{user:o}=await e.invoke(new i.a.auth.ImportBotAuthorization({apiId:s,apiHash:a,botAuthToken:r}));return o}(e,t,n);e._log.info("Signed in successfully as",r.a.getDisplayName(s))}async function l(e){try{return await e.invoke(new i.a.updates.GetState),!0}catch(e){return!1}}async function d(e,t,n){let s,a,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return f(e,t,n);throw s}else s=n.phoneNumber;const i=await g(e,t,s,n.forceSMS);if(a=i.phoneCodeHash,o=i.isCodeViaApp,"string"!=typeof a)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,u=!1;for(;;)try{try{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return d(e,t,n)}if(!r)throw new Error("Code is empty");const l=await e.invoke(new i.a.auth.SignIn({phoneNumber:s,phoneCodeHash:a,phoneCode:r}));if(l instanceof i.a.auth.AuthorizationSignUpRequired){u=!0,c=l.termsOfService;break}return l.user}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return p(e,t,n);n.onError(s)}if(u)for(;;)try{const[t,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new i.a.auth.SignUp({phoneNumber:s,phoneCodeHash:a,firstName:t,lastName:r}));return c&&await e.invoke(new i.a.help.AcceptTermsOfService({id:c.id})),o}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),d(e,t,n)}async function f(e,t,n){let s=!1;const a=(async()=>{for(;!s;){const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(!(t instanceof i.a.auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:a}=t;await Promise.race([n.qrCode({token:s,expires:a}),Object(o.sleep)(3e4)])}})(),r=new Promise(t=>{e.addEventHandler(e=>{e instanceof i.a.UpdateLoginToken&&t()},{build:e=>e})});try{await Promise.race([r,a])}catch(s){if("RESTART_AUTH"===s.message)return d(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(t instanceof i.a.auth.LoginTokenSuccess&&t.authorization instanceof i.a.auth.Authorization)return t.authorization.user;if(t instanceof i.a.auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new i.a.auth.ImportLoginToken({token:t.token}));if(n instanceof i.a.auth.LoginTokenSuccess&&n.authorization instanceof i.a.auth.Authorization)return n.authorization.user}}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return p(e,t,n);throw s}throw void 0}async function g(e,t,n,s=!1){try{const{apiId:a,apiHash:r}=t,o=await e.invoke(new i.a.auth.SendCode({phoneNumber:n,apiId:a,apiHash:r,settings:new i.a.CodeSettings}));if(!s||o.type instanceof i.a.auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof i.a.auth.SentCodeTypeApp};const c=await e.invoke(new i.a.auth.ResendCode({phoneNumber:n,phoneCodeHash:o.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof i.a.auth.SentCodeTypeApp}}catch(i){if("AUTH_RESTART"===i.message)return g(e,t,n,s);throw i}}async function p(e,t,n){for(;;)try{const t=await e.invoke(new i.a.account.GetPassword),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const a=await Object(c.computeCheck)(t,s),{user:r}=await e.invoke(new i.a.auth.CheckPassword({password:a}));return r}catch(e){n.onError(e)}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"downloadFile",(function(){return c}));var s=n(6),i=n.n(s),a=n(21),r=n(8);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}async function c(t,n,s){let{partSizeKb:o,fileSize:c,workers:l=1,end:d}=s;const{dcId:f,progressCallback:g,start:p=0}=s;d=d&&d{try{const s=await Promise.race([await y.send(new i.a.upload.GetFile({location:n,offset:w,limit:e,precise:t||void 0})),Object(r.sleep)(15e3).then(()=>Promise.reject(new Error("REQUEST_TIMEOUT")))]);if(g){if(g.isCanceled)throw new Error("USER_CANCELED");A+=1/m,g(A)}return!d&&s.bytes.lengthd)break}const I=(await Promise.all(_)).filter(Boolean),P=d?d+1-p:void 0;return e.concat(I,P)}class u{constructor(e){this.maxWorkers=e,o(this,"deferred",void 0),o(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=function(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"uploadFile",(function(){return o}));var s=n(6),i=n.n(s),a=n(8),r=n(21);async function o(t,n){const{file:s,onProgress:o}=n;let{workers:c}=n;const{name:u,size:l}=s,d=Object(a.readBigIntFromBuffer)(Object(a.generateRandomBytes)(8),!0,!0),f=l>10485760,g=1024*Object(r.getAppropriatedPartSize)(l),p=Math.floor((l+g-1)/g),h=e.from(await function(e){return new Response(e).arrayBuffer()}(s)),m=await t._borrowExportedSender(t.session.dcId);c&&l||(c=1),c>=p&&(c=p);let y=0;o&&o(y);for(let e=0;ep&&(n=p);for(let s=e;s{if(await m.send(f?new i.a.upload.SaveBigFilePart({fileId:d,filePart:s,fileTotalParts:p,bytes:e}):new i.a.upload.SaveFilePart({fileId:d,filePart:s,bytes:e})),o){if(o.isCanceled)throw new Error("USER_CANCELED");y+=1/p,o(y)}})())}try{await Promise.race([await Promise.all(t),Object(a.sleep)(15e3*c).then(()=>Promise.reject(new Error("TIMEOUT")))])}catch(t){if("TIMEOUT"===t.message){console.warn("Upload timeout. Retrying..."),e-=c;continue}throw t}}return f?new i.a.InputFileBig({id:d,parts:p,name:u}):new i.a.InputFile({id:d,parts:p,name:u,md5Checksum:""})}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"updateTwoFaSettings",(function(){return u}));var s=n(6),i=n.n(s),a=n(8),r=n(29),o=n(27),c=n.n(o);async function u(t,{isCheckPassword:n,currentPassword:s,newPassword:o,hint:u="",email:l,emailCodeCallback:d,onEmailCodeError:f}){if(!o&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(l&&(!d||!f))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const g=await t.invoke(new i.a.account.GetPassword);g.newAlgo instanceof i.a.PasswordKdfAlgoUnknown||(g.newAlgo.salt1=e.concat([g.newAlgo.salt1,Object(a.generateRandomBytes)(32)])),!g.hasPassword&&s&&(s=void 0);const p=s?await Object(r.computeCheck)(g,s):new i.a.InputCheckPasswordEmpty;if(n)await t.invoke(new i.a.auth.CheckPassword({password:p}));else try{await t.invoke(new i.a.account.UpdatePasswordSettings({password:p,newSettings:new i.a.account.PasswordInputSettings({newAlgo:g.newAlgo,newPasswordHash:o?await Object(r.computeDigest)(g.newAlgo,o):e.alloc(0),hint:u,email:l,newSecureSettings:void 0})}))}catch(e){if(!(e instanceof c.a.EmailUnconfirmedError))throw e;for(;;)try{const n=await d(e.codeLength);if(!n)throw new Error("Code is empty");await t.invoke(new i.a.account.ConfirmPasswordEmail({code:n}));break}catch(e){f(e)}}}}.call(this,n(12).Buffer)},function(e,t){e.exports="0.0.2"},function(e,t,n){const s=n(100),i=n(101);class a extends Error{}e.exports={NewMessage:s,StopPropagation:a,Raw:i}},function(e,t){},function(e,t,n){const{EventBuilder:s}=n(102);e.exports=class extends s{constructor(e={types:null,func:null}){super(),e.types?this.types=e.types:this.types=!0}build(e,t=null){return e}}},function(e,t){e.exports={EventBuilder:class{constructor(e={chats:null,blacklistChats:null,func:null}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e,t=null){}},EventCommon:class{}}},function(e,t,n){const s=n(30),i=n(104),a=n(105),r=n(106),o=n(107);e.exports={Memory:s,StringSession:i,CacheApiSession:a,LocalStorageSession:r,IdbSession:o}},function(e,t,n){(function(t){const s=n(30),i=n(32),a=n(25);class r extends s{constructor(e=null){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new a(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return t.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=t.from([this.dcId]),n=t.from(this.serverAddress),s=t.alloc(2);s.writeInt16BE(n.length,0);const i=t.alloc(2);return i.writeInt16BE(this.port,0),"1"+r.encode(t.concat([e,s,n,i,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r}).call(this,n(12).Buffer)},function(e,t,n){const s=n(42);e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open("GramJs")).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open("GramJs"),n=await t.match(e);return n?n.text():null}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open("GramJs")).put(t,n)}}},function(e,t,n){const s=n(42);e.exports=class extends s{async _delete(){return localStorage.removeItem(this._storageKey)}async _fetchFromCache(e){return localStorage.getItem(this._storageKey)}async _saveToCache(e,t){return localStorage.setItem(this._storageKey,t)}}},function(e,t,n){const s=n(42),i=n(108);e.exports=class extends s{async _delete(){return i.del("GramJs:"+this._storageKey)}async _fetchFromCache(){return i.get("GramJs:"+this._storageKey)}async _saveToCache(e){return i.set("GramJs:"+this._storageKey,e)}}},function(e,t,n){"use strict";function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=s(n);return(e,n)=>i.then(s=>n(s.transaction(t,e).objectStore(t)))}let a;function r(){return a||(a=i("keyval-store","keyval")),a}function o(e,t=r()){return t("readonly",t=>s(t.get(e)))}function c(e,t,n=r()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))}function u(e,t=r()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))}function l(e,t=r()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))}function d(e,t,n=r()){return n("readwrite",n=>new Promise((i,a)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),i(s(n.transaction))}catch(e){a(e)}}}))}function f(e,t=r()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))}function g(e=r()){return e("readwrite",e=>(e.clear(),s(e.transaction)))}function p(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)))}function h(e=r()){const t=[];return p(e,e=>t.push(e.key)).then(()=>t)}function m(e=r()){const t=[];return p(e,e=>t.push(e.value)).then(()=>t)}function y(e=r()){const t=[];return p(e,e=>t.push([e.key,e.value])).then(()=>t)}n.r(t),n.d(t,"clear",(function(){return g})),n.d(t,"createStore",(function(){return i})),n.d(t,"del",(function(){return f})),n.d(t,"entries",(function(){return y})),n.d(t,"get",(function(){return o})),n.d(t,"getMany",(function(){return l})),n.d(t,"keys",(function(){return h})),n.d(t,"promisifyRequest",(function(){return s})),n.d(t,"set",(function(){return c})),n.d(t,"setMany",(function(){return u})),n.d(t,"update",(function(){return d})),n.d(t,"values",(function(){return m}))},function(e,t,n){"use strict";n.r(t);var s={};n.r(s),n.d(s,"destroy",(function(){return g.a})),n.d(s,"disconnect",(function(){return g.b})),n.d(s,"downloadMedia",(function(){return g.c})),n.d(s,"fetchCurrentUser",(function(){return g.d})),n.d(s,"provideAuthPhoneNumber",(function(){return o.l})),n.d(s,"provideAuthCode",(function(){return o.j})),n.d(s,"provideAuthPassword",(function(){return o.k})),n.d(s,"provideAuthRegistration",(function(){return o.m})),n.d(s,"restartAuth",(function(){return o.n})),n.d(s,"restartAuthWithQr",(function(){return o.o})),n.d(s,"fetchChats",(function(){return c.j})),n.d(s,"fetchFullChat",(function(){return c.k})),n.d(s,"searchChats",(function(){return c.w})),n.d(s,"requestChatUpdate",(function(){return c.u})),n.d(s,"saveDraft",(function(){return c.v})),n.d(s,"clearDraft",(function(){return c.a})),n.d(s,"fetchChat",(function(){return c.h})),n.d(s,"updateChatMutedState",(function(){return c.H})),n.d(s,"createChannel",(function(){return c.b})),n.d(s,"joinChannel",(function(){return c.q})),n.d(s,"leaveChannel",(function(){return c.r})),n.d(s,"deleteChannel",(function(){return c.d})),n.d(s,"createGroupChat",(function(){return c.c})),n.d(s,"editChatPhoto",(function(){return c.g})),n.d(s,"toggleChatPinned",(function(){return c.z})),n.d(s,"toggleChatArchived",(function(){return c.y})),n.d(s,"toggleDialogUnread",(function(){return c.A})),n.d(s,"fetchChatFolders",(function(){return c.i})),n.d(s,"editChatFolder",(function(){return c.f})),n.d(s,"deleteChatFolder",(function(){return c.e})),n.d(s,"fetchRecommendedChatFolders",(function(){return c.n})),n.d(s,"getChatByUsername",(function(){return c.o})),n.d(s,"togglePreHistoryHidden",(function(){return c.B})),n.d(s,"updateChatDefaultBannedRights",(function(){return c.F})),n.d(s,"updateChatMemberBannedRights",(function(){return c.G})),n.d(s,"updateChatTitle",(function(){return c.I})),n.d(s,"updateChatAbout",(function(){return c.D})),n.d(s,"toggleSignatures",(function(){return c.C})),n.d(s,"updateChatAdmin",(function(){return c.E})),n.d(s,"fetchGroupsForDiscussion",(function(){return c.l})),n.d(s,"setDiscussionGroup",(function(){return c.x})),n.d(s,"migrateChat",(function(){return c.s})),n.d(s,"openChatByInvite",(function(){return c.t})),n.d(s,"fetchMembers",(function(){return c.m})),n.d(s,"fetchMessages",(function(){return u.g})),n.d(s,"fetchMessage",(function(){return u.e})),n.d(s,"sendMessage",(function(){return u.v})),n.d(s,"pinMessage",(function(){return u.q})),n.d(s,"unpinAllMessages",(function(){return u.y})),n.d(s,"deleteMessages",(function(){return u.b})),n.d(s,"deleteHistory",(function(){return u.a})),n.d(s,"markMessageListRead",(function(){return u.o})),n.d(s,"markMessagesRead",(function(){return u.p})),n.d(s,"requestThreadInfoUpdate",(function(){return u.r})),n.d(s,"searchMessagesLocal",(function(){return u.u})),n.d(s,"searchMessagesGlobal",(function(){return u.t})),n.d(s,"fetchWebPagePreview",(function(){return u.j})),n.d(s,"editMessage",(function(){return u.d})),n.d(s,"forwardMessages",(function(){return u.l})),n.d(s,"loadPollOptionResults",(function(){return u.n})),n.d(s,"sendPollVote",(function(){return u.w})),n.d(s,"findFirstMessageIdAfterDate",(function(){return u.k})),n.d(s,"fetchPinnedMessages",(function(){return u.h})),n.d(s,"fetchScheduledHistory",(function(){return u.i})),n.d(s,"sendScheduledMessages",(function(){return u.x})),n.d(s,"rescheduleMessage",(function(){return u.s})),n.d(s,"deleteScheduledMessages",(function(){return u.c})),n.d(s,"fetchMessageLink",(function(){return u.f})),n.d(s,"fetchFullUser",(function(){return v})),n.d(s,"fetchNearestCountry",(function(){return A})),n.d(s,"fetchTopUsers",(function(){return I})),n.d(s,"fetchContactList",(function(){return P})),n.d(s,"fetchUsers",(function(){return S})),n.d(s,"updateContact",(function(){return C})),n.d(s,"deleteUser",(function(){return M})),n.d(s,"fetchProfilePhotos",(function(){return k})),n.d(s,"fetchStickerSets",(function(){return B})),n.d(s,"fetchRecentStickers",(function(){return D})),n.d(s,"fetchFavoriteStickers",(function(){return x})),n.d(s,"fetchFeaturedStickers",(function(){return j})),n.d(s,"faveSticker",(function(){return N})),n.d(s,"fetchStickers",(function(){return F})),n.d(s,"fetchSavedGifs",(function(){return q})),n.d(s,"searchStickers",(function(){return L})),n.d(s,"installStickerSet",(function(){return H})),n.d(s,"uninstallStickerSet",(function(){return z})),n.d(s,"searchGifs",(function(){return K})),n.d(s,"fetchAnimatedEmojis",(function(){return V})),n.d(s,"fetchStickersForEmoji",(function(){return G})),n.d(s,"checkChatUsername",(function(){return $})),n.d(s,"setChatUsername",(function(){return Z})),n.d(s,"updatePrivateLink",(function(){return Y})),n.d(s,"updateProfile",(function(){return fe})),n.d(s,"checkUsername",(function(){return ge})),n.d(s,"updateUsername",(function(){return pe})),n.d(s,"fetchBlockedContacts",(function(){return _e})),n.d(s,"blockContact",(function(){return we})),n.d(s,"unblockContact",(function(){return ve})),n.d(s,"updateProfilePhoto",(function(){return he})),n.d(s,"uploadProfilePhoto",(function(){return me})),n.d(s,"fetchWallpapers",(function(){return ye})),n.d(s,"uploadWallpaper",(function(){return be})),n.d(s,"fetchAuthorizations",(function(){return Ae})),n.d(s,"terminateAuthorization",(function(){return Ie})),n.d(s,"terminateAllAuthorizations",(function(){return Pe})),n.d(s,"loadNotificationsSettings",(function(){return Se})),n.d(s,"updateContactSignUpNotification",(function(){return Ce})),n.d(s,"updateNotificationSettings",(function(){return Me})),n.d(s,"fetchLanguages",(function(){return ke})),n.d(s,"fetchLangPack",(function(){return Ee})),n.d(s,"fetchPrivacySettings",(function(){return Re})),n.d(s,"setPrivacySettings",(function(){return Te})),n.d(s,"registerDevice",(function(){return Oe})),n.d(s,"unregisterDevice",(function(){return Ue})),n.d(s,"getPasswordInfo",(function(){return te})),n.d(s,"checkPassword",(function(){return se})),n.d(s,"clearPassword",(function(){return ie})),n.d(s,"updatePassword",(function(){return ae})),n.d(s,"updateRecoveryEmail",(function(){return re})),n.d(s,"provideRecoveryEmailCode",(function(){return oe})),n.d(s,"answerCallbackButton",(function(){return De.a})),n.d(s,"validateRequestedInfo",(function(){return je})),n.d(s,"sendPaymentForm",(function(){return Ne})),n.d(s,"getPaymentForm",(function(){return Fe})),n.d(s,"getReceipt",(function(){return Ve}));var i=n(4),a=n(28),r=n(26),o=n(17),c=n(7),u=n(10),l=n(15),d=n.n(l),f=n(0),g=n(1),p=n(2),h=n(13),m=n(3),y=n(19),b=n(5),_=n(16);let w;async function v({id:e,accessHash:t}){const n=Object(p.g)(e,t);if(!(n instanceof f.Api.InputUser))return;const s=await Object(g.g)(new f.Api.users.GetFullUser({id:n}));if(!s)return;const i=Object(h.b)(s);w({"@type":"updateUser",id:e,user:{fullInfo:i.fullInfo}})}async function A(){const e=await Object(g.g)(new f.Api.help.GetNearestDc);return e?e.country:void 0}async function I({hash:e=0}){const t=await Object(g.g)(new f.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof f.Api.contacts.TopPeers))return;const n=t.users.map(h.a).filter(e=>!!e&&!e.isSelf),s=n.map(({id:e})=>e);return{hash:Object(p.q)(s),ids:s,users:n}}async function P({hash:e=0}){const t=await Object(g.g)(new f.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof f.Api.contacts.ContactsNotModified))return t.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),{hash:Object(p.q)([t.savedCount,...t.contacts.map(({userId:e})=>e)]),users:t.users.map(h.a).filter(Boolean),chats:t.users.map(e=>Object(m.d)(e)).filter(Boolean)}}async function S({users:e}){const t=await Object(g.g)(new f.Api.users.GetUsers({id:e.map(({id:e,accessHash:t})=>Object(p.i)(e,t))}));if(t&&t.length)return t.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),t.map(h.a).filter(Boolean)}function C({phone:e,firstName:t,lastName:n}){return Object(g.g)(new f.Api.contacts.ImportContacts({contacts:[Object(p.e)({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function M({id:e,accessHash:t}){const n=Object(p.g)(e,t);if(!(n instanceof f.Api.InputUser))return;await Object(g.g)(new f.Api.contacts.DeleteContacts({id:[n]}))&&w({"@type":"deleteUser",id:e})}async function k(e,t){if(e){const{id:t,accessHash:n}=e,s=await Object(g.g)(new f.Api.photos.GetUserPhotos({userId:Object(p.g)(t,n),limit:i.t,offset:0,maxId:d()("0")}));if(!s)return;return function(e){e.photos.forEach(_.b)}(s),{photos:s.photos.filter(e=>e instanceof f.Api.Photo).map(y.a)}}const n=await Object(u.u)({chatOrUser:t,type:"profilePhoto",limit:i.t});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map(e=>e.content.action.photo).filter(Boolean),users:a}}var E=n(22),R=n(9);let O,U,T;async function B({hash:e}){const t=await Object(g.g)(new f.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.AllStickersNotModified))return t.sets.forEach(e=>{e.thumb&&(b.a.stickerSets[String(e.id)]=e)}),{hash:t.hash,sets:t.sets.map(E.b)}}async function D({hash:e}){const t=await Object(g.g)(new f.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:W(t.stickers)}}async function x({hash:e}){const t=await Object(g.g)(new f.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:W(t.stickers)}}async function j({hash:e}){const t=await Object(g.g)(new f.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(E.c)}}async function N({sticker:e,unfave:t}){const n=new f.Api.messages.FaveSticker({id:Object(p.f)(e),unfave:t});await Object(g.g)(n)&&O({"@type":"updateFavoriteStickers"})}async function F({stickerSetId:e,accessHash:t}){const n=await Object(g.g)(new f.Api.messages.GetStickerSet({stickerset:Object(p.l)(e,t)}));var s;if(n)return{set:Object(E.b)(n.set),stickers:W(n.documents),packs:(s=n.packs,s.reduce((e,{emoticon:t,documents:n})=>(e[t]=n.map(e=>Object(E.a)(b.a.documents[String(e)])).filter(Boolean),e),{}))}}async function V(){const e=await Object(g.g)(new f.Api.messages.GetStickerSet({stickerset:new f.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:Object(E.b)(e.set),stickers:W(e.documents)}}async function L({query:e,hash:t}){const n=await Object(g.g)(new f.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof f.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(E.c)}}async function q({hash:e}){const t=await Object(g.g)(new f.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof f.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:J(t.gifs)}}async function H({stickerSetId:e,accessHash:t}){await Object(g.g)(new f.Api.messages.InstallStickerSet({stickerset:Object(p.l)(e,t)}))&&O({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function z({stickerSetId:e,accessHash:t}){await Object(g.g)(new f.Api.messages.UninstallStickerSet({stickerset:Object(p.l)(e,t)}))&&O({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function K({query:e,offset:t=""}){if(!U){const e=await Object(g.g)(new f.Api.help.GetConfig);if(!e)return;const t=await Object(g.g)(new f.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof f.Api.User))return;U=new f.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Object(g.g)(new f.Api.messages.GetInlineBotResults({bot:U,peer:new f.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map(e=>{if(e instanceof f.Api.BotInlineMediaResult)return e.document}).filter(Boolean);return{nextOffset:n.nextOffset,gifs:J(s)}}async function G({emoji:e,hash:t=0}){const n=await Object(g.g)(new f.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof f.Api.messages.StickersNotModified))return{stickers:W(n.stickers),hash:n.hash}}function W(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(E.a)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}function J(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(R.m)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}async function $({username:e}){try{return await Object(g.g)(new f.Api.channels.CheckUsername({channel:new f.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Z({chat:e,username:t}){await Object(g.g)(new f.Api.channels.UpdateUsername({channel:Object(p.g)(e.id,e.accessHash),username:t}))&&T({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Y({chat:e}){const t=await Object(g.g)(new f.Api.messages.ExportChatInvite({peer:Object(p.i)(e.id,e.accessHash)}));t&&t instanceof f.Api.ChatInviteExported&&T({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const Q={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"},X={};let ee;async function te(){const e=await Object(g.g)(new f.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function ne(e){return ee({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise((e,t)=>{X.resolve=e,X.reject=t})}async function se(e){try{return await Object(g.h)({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ce(e),!1}}async function ie(e){try{return await Object(g.h)({currentPassword:e}),!0}catch(e){return ce(e),!1}}async function ae(e,t,n,s){try{return await Object(g.h)({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:ne,onEmailCodeError:ce}),!0}catch(e){return ce(e),!1}}async function re(e,t){try{return await Object(g.h)({currentPassword:e,newPassword:e,email:t,emailCodeCallback:ne,onEmailCodeError:ce}),!0}catch(e){return ce(e),!1}}function oe(e){X.resolve(e)}function ce(e){let t;if(e instanceof f.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=Q[e.message];t||(t="Unexpected Error",i.f&&console.error(e)),ee({"@type":"updateTwoFaError",message:t})}var ue=n(24),le=n(18),de=n(14);function fe({firstName:e,lastName:t,about:n}){return Object(g.g)(new f.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function ge(e){return Object(g.g)(new f.Api.account.CheckUsername({username:e}))}function pe(e){return Object(g.g)(new f.Api.account.UpdateUsername({username:e}))}async function he(e){const t=await Object(g.i)(e);return Object(g.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function me(e){const t=await Object(g.i)(e);await Object(g.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function ye(e){const t=await Object(g.g)(new f.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof f.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter(e=>e instanceof f.Api.WallPaper&&e.document instanceof f.Api.Document&&(!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach(e=>{b.a.documents[String(e.document.id)]=e.document}),{hash:t.hash,wallpapers:n.map(ue.b).filter(Boolean)}}async function be(e){const t=await Object(g.i)(e),n=await Object(g.g)(new f.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new f.Api.WallPaperSettings}));if(!(n&&n instanceof f.Api.WallPaper))return;const s=Object(ue.b)(n);return s?(b.a.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function _e(){const e=await Object(g.g)(new f.Api.contacts.GetBlocked({limit:i.e}));if(e)return Be(e),{users:e.users.map(h.a).filter(Boolean),chats:e.chats.map(e=>Object(m.d)(e,void 0,!0)).filter(Boolean),blockedIds:e.blocked.map(e=>Object(m.k)(e.peerId)),totalCount:e instanceof f.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function we(e){return Object(g.g)(new f.Api.contacts.Block({id:Object(p.o)(e)}))}function ve(e,t){return Object(g.g)(new f.Api.contacts.Unblock({id:Object(p.i)(e,t)}))}async function Ae(){const e=await Object(g.g)(new f.Api.account.GetAuthorizations);if(e)return e.authorizations.map(ue.a)}function Ie(e){return Object(g.g)(new f.Api.account.ResetAuthorization({hash:d()(e)}))}function Pe(){return Object(g.g)(new f.Api.auth.ResetAuthorizations)}async function Se(){const[e,t,n,s]=await Promise.all([Object(g.g)(new f.Api.account.GetContactSignUpNotification),Object(g.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyUsers})),Object(g.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyChats})),Object(g.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyBroadcasts}))]);if(!t||!n||!s)return!1;const{silent:i,muteUntil:a,showPreviews:r}=t,{silent:o,muteUntil:c,showPreviews:u}=n,{silent:l,muteUntil:d,showPreviews:p}=s;return{hasContactJoinedNotifications:!e,hasPrivateChatsNotifications:!(i||"number"==typeof a&&Date.now()<1e3*a),hasPrivateChatsMessagePreview:r,hasGroupNotifications:!(o||"number"==typeof c&&Date.now()<1e3*c),hasGroupMessagePreview:u,hasBroadcastNotifications:!(l||"number"==typeof d&&Date.now()<1e3*d),hasBroadcastMessagePreview:p}}function Ce(e){return Object(g.g)(new f.Api.account.SetContactSignUpNotification({silent:e}))}function Me(e,{isSilent:t,isShowPreviews:n}){let s;s="contact"===e?new f.Api.InputNotifyUsers:"group"===e?new f.Api.InputNotifyChats:new f.Api.InputNotifyBroadcasts;const i={showPreviews:n,silent:t,muteUntil:t?2**31-1:void 0};return Object(g.g)(new f.Api.account.UpdateNotifySettings({peer:s,settings:new f.Api.InputPeerNotifySettings(i)}))}async function ke(){const e=await Object(g.g)(new f.Api.langpack.GetLanguages({langPack:i.h}));if(e)return e.map(le.b)}async function Ee({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map(e=>Object(g.g)(new f.Api.langpack.GetLangPack({langPack:e,langCode:t}))))).filter(Boolean).map(e=>Object(de.a)(e.strings.map(le.b),"key"));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function Re(e){const t=Object(p.k)(e),n=await Object(g.g)(new f.Api.account.GetPrivacy({key:t}));if(n)return Be(n),Object(ue.d)(n.rules)}function Oe(e){const t=Object(g.e)().session.getAuthKey().getKey();return Object(g.g)(new f.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Ue(e){return Object(g.g)(new f.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function Te(e,t){const n=Object(p.k)(e),s=[];switch(t.allowedUsers&&s.push(new f.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map(({id:e,accessHash:t})=>Object(p.i)(e,t))})),t.allowedChats&&s.push(new f.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map(({id:e})=>-e)})),t.blockedUsers&&s.push(new f.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map(({id:e,accessHash:t})=>Object(p.i)(e,t))})),t.blockedChats&&s.push(new f.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map(({id:e})=>-e)})),t.visibility){case"everybody":s.push(new f.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new f.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new f.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new f.Api.InputPrivacyValueDisallowAll)}const i=await Object(g.g)(new f.Api.account.SetPrivacy({key:n,rules:s}));if(i)return Be(i),Object(ue.d)(i.rules)}function Be(e){e.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof f.Api.Chat||e instanceof f.Api.Channel)&&(b.a.chats[e.id]=e)})}var De=n(72);function xe(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 je({messageId:e,requestInfo:t,shouldSave:n}){const s=await Object(g.g)(new f.Api.payments.ValidateRequestedInfo({msgId:e,save:n||void 0,info:Object(p.p)(t)}));if(!s)return;const{id:i,shippingOptions:a}=s;return i?{id:i,shippingOptions:xe(a)}:void 0}function Ne({messageId:e,requestedInfoId:t,shippingOptionId:n,credentials:s}){return Object(g.g)(new f.Api.payments.SendPaymentForm({msgId:e,requestedInfoId:t,shippingOptionId:n,credentials:new f.Api.InputPaymentCredentials({save:s.save,data:new f.Api.DataJSON({data:JSON.stringify(s.data)})})}),!0)}async function Fe({messageId:e}){const t=await Object(g.g)(new f.Api.payments.GetPaymentForm({msgId:e}));if(t)return function(e){const{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,nativeParams:a,savedInfo:r,invoice:o}=e,{test:c,nameRequested:u,phoneRequested:l,emailRequested:d,shippingAddressRequested:f,flexible:g,phoneToProvider:p,emailToProvider:h,currency:m,prices:y}=o,b=y.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),_=a?JSON.parse(a.data):{};return{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,savedInfo:r,invoice:{test:c,nameRequested:u,phoneRequested:l,emailRequested:d,shippingAddressRequested:f,flexible:g,phoneToProvider:p,emailToProvider:h,currency:m,prices:b},nativeParams:{needCardholderName:_.need_cardholder_name,needCountry:_.need_country,needZip:_.need_zip,publishableKey:_.publishable_key}}}(t)}async function Ve(e){const t=await Object(g.g)(new f.Api.payments.GetPaymentReceipt({msgId:e}));if(t)return function(e){const{invoice:t,info:n,shipping:s,currency:i,totalAmount:a,credentialsTitle:r}=e,{shippingAddress:o,phone:c,name:u}=n||{},{prices:l}=t,d=l.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}));let f,g;return s&&(f=s.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),g=s.title),{currency:i,prices:d,info:{shippingAddress:o,phone:c,name:u},totalAmount:Number(a.value),credentialsTitle:r,shippingPrices:f,shippingMethod:g}}(t)}let Le;async function qe(e,t=""){Le=e,Object(r.a)(We),Object(o.a)(We),Object(c.p)(We),Object(u.m)(We),function(e){w=e}(We),function(e){O=e}(We),function(e){T=e}(We),function(e){ee=e}(We),await Object(g.f)(t,We)}const He=Object(a.c)((function(e){if(!Ge||e!==Ke)return;const t=Ge;Ge=void 0,t.forEach(Le)}));let ze,Ke,Ge;function We(e){Ge?Ge.push(e):Ge=[e],ze&&!i.b.has(e["@type"])||(ze=Object(a.b)(He,i.c,!0),Ke=Math.random()),ze(Ke)}self.onerror=e=>{console.error(e),Ze({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),Ze({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const Je=new Map;function $e(e){Ze({type:"update",update:e})}function Ze(e,t){t?postMessage(e,[t]):postMessage(e)}i.f&&console.log(">>> FINISH LOAD WORKER"),onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await qe($e,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:a}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Ze({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Je.set(e,t),a.push(t)}const t=await function(e,...t){return s[e](...t)}(n,...a),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Ze({type:"methodResponse",messageId:e,response:t},i)}catch(t){i.f&&console.error(t),e&&Ze({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Je.delete(e);break}case"cancelProgress":{const e=Je.get(t.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=0cfac43ee01937a2bf09.worker.js.map \ No newline at end of file +//# sourceMappingURL=e1066b23c5448d0199e4.worker.js.map \ No newline at end of file diff --git a/dist/0cfac43ee01937a2bf09.worker.js.LICENSE.txt b/dist/e1066b23c5448d0199e4.worker.js.LICENSE.txt similarity index 100% rename from dist/0cfac43ee01937a2bf09.worker.js.LICENSE.txt rename to dist/e1066b23c5448d0199e4.worker.js.LICENSE.txt diff --git a/dist/0cfac43ee01937a2bf09.worker.js.map b/dist/e1066b23c5448d0199e4.worker.js.map similarity index 99% rename from dist/0cfac43ee01937a2bf09.worker.js.map rename to dist/e1066b23c5448d0199e4.worker.js.map index bc4e8d0d..b0e1a18a 100644 --- a/dist/0cfac43ee01937a2bf09.worker.js.map +++ b/dist/e1066b23c5448d0199e4.worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/process/browser.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","sessionId","_onUpdate","DEBUG","log","session","IS_TEST","LocalStorageSession","IdbSession","process","useWSS","additionalDcsDisabled","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","newSessionId","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","result","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","length","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","nonStrippedSizes","sizes","PhotoSize","PhotoCachedSize","smallSize","find","largeSize","ChatPhoto","photoSmall","location","photoBig","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restricted","restrictionReason","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","toString","restrictionReasons","targetReason","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","UserProfilePhoto","photoId","volumeId","localId","buildChatMember","member","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatInviteLink","exportedInvite","ChatInviteExported","link","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateChatUserTyping","UpdateChannelUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","readBufferFromBigInt","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","api","fromReader","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","byte","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","firstMessageId","Messages","offsetId","offsetIdOffset","offsetIdIndex","findIndex","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","discussionChatId","topMessageId","ChannelMessages","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","addOffset","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","subarray","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","reduce","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","flags","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","patched","JPEG_HEADER","RegExp","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","cdn","ipAddress","port","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","UpdateUserTyping","typingStatus","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","showPreviews","peerType","isShowPreviews","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","RPCError","rpcErrorRe","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","setDC","serverAddress","_authKey","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","Logger","BinaryWriter","PromisedWebSockets","MessagePacker","AsyncQueue","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","before","tlMessage","MTProtoPlainSender","doAuthentication","MTProtoSender","Connection","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","_storageKey","_authKeys","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","sessionData","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","fromLine","line","argsMatch","findAll","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","regex","matches","exec","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","_stream","getValue","RPCResult","RpcError","reqMsgId","body","innerCode","LAYER","mutex","Mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","send","onmessage","release","acquire","logger","_state","_queue","_pendingStates","_ready","setReady","append","promise","catch","finally","extend","states","batch","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","after","writeDataAsMessage","containerId","rejectAll","requestState","canGet","resolveGet","canPush","resolvePush","returned","MtProtoPlainSender","MTProtoState","Helpers","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","DEFAULT_OPTIONS","_connection","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","plain","setKey","time_offset","timeOffset","ack","msgIds","encryptMessageData","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","innerMessage","pong","badSalt","badMsgId","newServerSalt","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","nanoseconds","newMsgId","correctMsgId","bad","old","aes_ige","ige","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","ys","condition","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","webpackPolyfill","deprecate","paths","children","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","deviceModel","systemVersion","appVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","_lastRequest","GetState","DC","_cleanupBorrowedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","race","sequentialUpdates","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","endianness","hostname","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","navigator","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","partSizeKb","partSize","partsCount","_borrowExportedSender","foreman","Foreman","promises","hasEnded","requestWorker","releaseWorker","GetFile","precise","totalLength","maxWorkers","activeWorkers","deferred","_resolve","createDeferred","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","EventCommon","Memory","StringSession","CacheApiSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","loadNotificationsSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS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WG23F,CAAQzlG,KAAS8N,IAClC,YAAE3I,GAAqC,iBAAblC,GAAyB,gBAAiBA,GAAYA,GAAa,GAE/F04B,GACFupE,GAAa,CACXtiG,KAAM,iBACN+4B,YACA14B,YACCkC,GAEL,MAAOqI,GACHvD,KAEFpG,QAAQ2J,MAAMA,GAGZmuB,GACFupE,GAAa,CACXtiG,KAAM,iBACN+4B,YACAnuB,MAAO,CAAEvG,QAASuG,EAAMvG,WAK1B00B,GACFwpE,GAAc5gG,OAAOo3B,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAM6rD,EAAW2d,GAAc7kG,IAAI0D,EAAK23B,WACpC6rD,IACgBA,EDzCPr/C,YAAa,GC4C1B","file":"0cfac43ee01937a2bf09.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 109);\n","const Api = require('./tl/api')\nconst TelegramClient = require('./client/TelegramClient')\nconst connection = require('./network')\nconst tl = require('./tl')\nconst version = require('./Version')\nconst events = require('./events')\nconst utils = require('./Utils')\nconst errors = require('./errors')\nconst sessions = require('./sessions')\nconst extensions = require('./extensions')\nconst helpers = require('./Helpers')\n\nmodule.exports = {\n Api, TelegramClient, sessions, connection, extensions,\n tl, version, events, utils, errors, helpers,\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : 'image/jpeg';\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = 'image/jpeg';\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport { ApiMediaFormat, ApiOnProgress, OnApiUpdate } from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(sessionId: string, _onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n const session = IS_TEST\n ? new sessions.LocalStorageSession(sessionId)\n : new sessions.IdbSession(sessionId);\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n }\n\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n });\n\n const newSessionId = await session.save();\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED as ', newSessionId);\n }\n\n onAuthReady(newSessionId);\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ${request.className} ERROR: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId } = photo;\n const nonStrippedSizes = photo.sizes\n .filter((s: any): s is (GramJs.PhotoSize | GramJs.PhotoCachedSize) => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoCachedSize;\n });\n\n if (!nonStrippedSizes.length) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const smallSize = nonStrippedSizes.find((s) => s.type === 'a');\n const largeSize = nonStrippedSizes.find((s) => s.type === 'c') || nonStrippedSizes.find((s) => s.type === 'b');\n\n if (!smallSize || !largeSize) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n return new GramJs.ChatPhoto({\n dcId,\n photoSmall: smallSize && smallSize.location,\n photoBig: largeSize && largeSize.location,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatMember,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiRestrictionReason,\n ApiChatFolder,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isPeerChat,\n isPeerUser,\n isInputPeerUser,\n isInputPeerChat,\n isInputPeerChannel,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n if (peerEntity instanceof GramJs.User) {\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: peerEntity.migratedTo.accessHash.toString(),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: any) {\n if (photo instanceof GramJs.UserProfilePhoto) {\n return photo.photoId.toString();\n } else if (photo instanceof GramJs.ChatPhoto) {\n const { dcId, photoSmall: { volumeId, localId } } = photo;\n return `${dcId}-${volumeId}-${localId}`;\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember {\n return {\n userId: member.userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n): ApiChatMember[] | undefined {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember);\n }\n\n return undefined;\n}\n\nexport function buildChatInviteLink(exportedInvite: GramJs.TypeExportedChatInvite) {\n return exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n}\n\nexport function buildChatTypingStatus(update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'recording a video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'uploading a video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'recording a voice message';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'uploading a voice message';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'uploading a photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'uploading a file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'playing a game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'recording a round video';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'uploading a round video';\n }\n\n return {\n action,\n ...(update instanceof GramJs.UpdateChatUserTyping && { userId: update.userId }),\n ...(update instanceof GramJs.UpdateChannelUserTyping && { userId: update.userId }),\n timestamp: Date.now(),\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\n","const {\n parseTl,\n serializeBytes,\n serializeDate\n} = require('./generationHelpers')\nconst { readBufferFromBigInt,toSignedLittleBuffer } = require('../Helpers')\n\nconst tlContent = require('./apiTl.js')\nconst schemeContent = require('./schemaTl.js')\n\n/*CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined\n\nconst CACHE_KEY = 'GramJs:apiCache'\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache()\n\n if (fromCache) {\n definitions = fromCache\n } else {\n definitions = loadFromTlSchemas()\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions))\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests)\n )\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY)\n return jsonCache && JSON.parse(jsonCache)\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent)\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent)\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema)\n const requests = [].concat(functionParamsApi, functionParamsSchema)\n\n return { constructors, requests }\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 }\n\n Object.keys(obj2).forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key]\n } else {\n Object.assign(result[key], obj2[key])\n }\n })\n\n return result\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109)\n const constructors = []\n const functions = []\n for (const d of f) {\n d.isFunction ? functions.push(d) : constructors.push(d)\n }\n return [constructors, functions]\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int':\n const i = Buffer.alloc(4)\n i.writeInt32LE(x, 0)\n return i\n case 'long':\n return toSignedLittleBuffer(x, 8)\n case 'int128':\n return toSignedLittleBuffer(x, 16)\n case 'int256':\n return toSignedLittleBuffer(x, 32)\n case 'double':\n const d = Buffer.alloc(8)\n d.writeDoubleLE(x, 0)\n return d\n case 'string':\n return serializeBytes(x)\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex')\n case 'true':\n return Buffer.alloc(0)\n case 'bytes':\n return serializeBytes(x)\n case 'date':\n return serializeDate(x)\n default:\n return x.getBytes()\n }\n}\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt()\n }\n const temp = []\n const len = reader.readInt()\n arg.isVector = false\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg))\n }\n arg.isVector = true\n return temp\n } else if (arg.flagIndicator) {\n return reader.readInt()\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt()\n case 'long':\n return reader.readLong()\n case 'int128':\n return reader.readLargeInt(128)\n case 'int256':\n return reader.readLargeInt(256)\n case 'double':\n return reader.readDouble()\n case 'string':\n return reader.tgReadString()\n case 'Bool':\n return reader.tgReadBool()\n case 'true':\n return true\n case 'bytes':\n return reader.tgReadBytes()\n case 'date':\n return reader.tgReadDate()\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject()\n } else {\n return api.constructors[arg.type].fromReader(reader)\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {}\n for (const classParams of params) {\n const { name, constructorId, subclassOfId, argsConfig, namespace, result } = classParams\n const fullName = [namespace, name].join('.').replace(/^\\./, '')\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId\n static SUBCLASS_OF_ID = subclassOfId\n static className = fullName\n static classType = classesType\n\n CONSTRUCTOR_ID = constructorId\n SUBCLASS_OF_ID = subclassOfId\n className = fullName\n classType = classesType\n\n constructor(args) {\n args = args || {}\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName]\n })\n }\n\n static fromReader(reader) {\n\n const args = {}\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName]\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args['flags'] & 1 << arg.flagIndex)\n continue\n }\n if (args['flags'] & 1 << arg.flagIndex) {\n args[argName] = getArgFromReader(reader, arg)\n } else {\n args[argName] = null\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags'\n }\n args[argName] = getArgFromReader(reader, arg)\n }\n }\n }\n return new VirtualClass(args)\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID\n const c = Buffer.alloc(4)\n c.writeUInt32LE(idForBytes, 0)\n const buffers = [c]\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg]===false&&argsConfig[arg].type===\"true\") || this[arg]===null || this[arg]===undefined){\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'))\n }\n const l = Buffer.alloc(4)\n l.writeInt32LE(this[arg].length, 0)\n buffers.push(l, Buffer.concat(this[arg].map(x => argToBytes(x, argsConfig[arg].type))))\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4))\n } else {\n let flagCalculate = 0\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f]===false&&argsConfig[f].type===\"true\") || this[f]===undefined || this[f]===null) {\n flagCalculate |= 0\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex\n }\n }\n }\n const f = Buffer.alloc(4)\n f.writeUInt32LE(flagCalculate, 0)\n buffers.push(f)\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type))\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1))\n boxed = boxed === boxed.toUpperCase()\n if (!boxed) {\n buffers.shift()\n }\n }\n }\n }\n\n }\n return Buffer.concat(buffers)\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance')\n }\n\n const m = result.match(/Vector<(int|long)>/)\n if (m) {\n reader.readInt()\n let temp = []\n let len = reader.readInt()\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt())\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong())\n }\n }\n return temp\n } else {\n return reader.tgReadObject()\n }\n }\n\n /*CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n }*/\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {}\n }\n classes[namespace][name] = VirtualClass\n\n } else {\n classes[name] = VirtualClass\n }\n }\n\n return classes\n}\n\nmodule.exports = buildApiFromTlSchema()\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildChatInviteLink,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n lastMessage,\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n inviteLink: buildChatInviteLink(exportedInvite),\n canViewMembers: true,\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: number; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n userId,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as number,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter = 'kicked' | 'admin' | 'recent';\n\nexport async function fetchMembers(\n chatId: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n","const crypto = require('./crypto/crypto')\nconst BigInt = require('big-integer')\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer)\n const bytesNumber = randBuffer.length\n if (little) {\n randBuffer = randBuffer.reverse()\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16)\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)))\n }\n return bigInt\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big)\n const byteArray = []\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i).and(255)\n }\n return Buffer.from(byteArray)\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt)\n const bitLength = bigInt.bitLength()\n\n const bytes = Math.ceil(bitLength / 8)\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert')\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned')\n }\n let below = false\n if (bigInt.lesser(BigInt(0))) {\n below = true\n bigInt = bigInt.abs()\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0')\n let l = Buffer.from(hex, 'hex')\n if (little) {\n l = l.reverse()\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false\n if (l[0] !== 0) {\n l[0] -= 1\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true\n continue\n }\n if (reminder) {\n l[i] -= 1\n reminder = false\n }\n l[i] = 255 - l[i]\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1]\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i]\n }\n }\n }\n return l\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed)\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m)\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count))\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n/*CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16)\n newNonce = toSignedLittleBuffer(newNonce, 32)\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce]))\n ])\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)])\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)])\n return {\n key: keyBuffer,\n iv: ivBuffer\n }\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4)\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1')\n shaSum.update(data)\n return shaSum.digest()\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256')\n shaSum.update(data)\n return shaSum.digest()\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n)\n let result = BigInt.one\n let x = a\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2))\n b = b.divide(BigInt(2))\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x)\n result = result.remainder(n)\n }\n x = x.multiply(x)\n x = x.remainder(n)\n }\n return result\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length\n const byteLength = Math.floor((bits + 8 - 1) / 8)\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed)\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min)\n max = Math.floor(max)\n return Math.floor(Math.random() * (max - min + 1)) + min\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c\n const crcTable = []\n for (let n = 0; n < 256; n++) {\n c = n\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1))\n }\n crcTable[n] = c\n }\n return crcTable\n}\n\nlet crcTable = null\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable()\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf)\n }\n let crc = -1\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index]\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8)\n }\n return (crc ^ (-1)) >>> 0\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n //calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n //isArrayLike,\n toSignedLittleBuffer,\n convertToLittle\n\n}\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\n ]);\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %product%`;\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_IMAGE_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n // Not sure if there is an easier way to do this\n let firstMessageId: number | undefined;\n if (result.messages.length) {\n if (result instanceof GramJs.messages.Messages) {\n firstMessageId = result.messages[result.messages.length - 1].id;\n } else if (pagination.offsetId && result.offsetIdOffset) {\n const offsetIdIndex = result.messages.findIndex((m) => m.id === pagination.offsetId);\n const lastIndex = result.messages.length - offsetIdIndex;\n if (lastIndex + result.offsetIdOffset >= result.count) {\n firstMessageId = result.messages[result.messages.length - 1].id;\n }\n }\n }\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n firstMessageId,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n}) {\n const isScheduled = message.date * 1000 > Date.now();\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate(chat);\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n });\n });\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n hash: calculateResultHash(messages.map((message) => message.id)),\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","import { ApiDocument } from './messages';\n\nexport * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\n\nexport interface ApiOnProgress {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface ApiAttachment {\n blobUrl: string;\n filename: string;\n mimeType: string;\n size: number;\n quick?: {\n width: number;\n height: number;\n duration?: number;\n };\n voice?: {\n duration: number;\n waveform: number[];\n };\n previewBlobUrl?: string;\n}\n\nexport interface ApiWallpaper {\n slug: string;\n document: ApiDocument;\n}\n\nexport interface ApiSession {\n hash: string;\n isCurrent: boolean;\n isOfficialApp: boolean;\n isPasswordPending: boolean;\n deviceModel: string;\n platform: string;\n systemVersion: string;\n appName: string;\n appVersion: string;\n dateCreated: number;\n dateActive: number;\n ip: string;\n country: string;\n region: string;\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo, notifySettings: { silent, muteUntil },\n } = mtpUserFull;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isMuted,\n ...(botInfo && { botDescription: botInfo.description }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","var bigInt = (function (undefined) {\r\n \"use strict\";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\n\r\n var supportsNativeBigInt = typeof BigInt === \"function\";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === \"undefined\") return Integer[0];\r\n if (typeof radix !== \"undefined\") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === \"number\") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === \"number\") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error(\"Cannot divide by zero\");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === \"number\") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === \"number\") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === \"number\") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don't know if it's prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === \"number\" ? v | LOBMASK_I :\r\n typeof v === \"bigint\" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === \"-\") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === \"1\" && absBase === 1) continue;\r\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === \"-\";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === \"<\") {\r\n var start = i;\r\n do { i++; } while (text[i] !== \">\" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + \" is not a valid character\");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return \"<\" + digit + \">\";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join('');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? \"-\" : \"\";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error(\"Invalid integer: \" + v);\r\n }\r\n var sign = v[0] === \"-\";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === \"+\") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(\".\");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\r\n text += (new Array(exp + 1)).join(\"0\");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? \"-\" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === \"number\") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === \"string\") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === \"bigint\") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid Phone Number',\n PHONE_CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady(sessionId: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateReady'),\n sessionId,\n });\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","export function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","const api = require('./api')\nconst { serializeBytes, serializeDate } = require('./generationHelpers')\nconst patched = null\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n patched,\n serializeBytes,\n serializeDate\n}\n","const { constructors } = require('./tl')\n\nconst USERNAME_RE = new RegExp('@|(?:https?:\\\\/\\\\/)?(?:www\\\\.)?' +\n '(?:telegram\\\\.(?:me|dog)|t\\\\.me)\\\\/(@|joinchat\\\\/)?')\n\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex')\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex')\n\nconst TG_JOIN_RE = new RegExp('tg:\\\\/\\\\/(join)\\\\?invite=')\n\nconst VALID_USERNAME_RE = new RegExp('^([a-z]((?!__)[\\\\w\\\\d]){3,30}[a-z\\\\d]|gif|vid|' +\n 'pic|bing|wiki|imdb|bold|vote|like|coub)$')\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`)\n}\n\n/**\n Gets the input peer for the given \"entity\" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn't a supported type\n or if ``check_hash is True`` but the entity's ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``check_hash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they're doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\n if (allowSelf && 'inputEntity' in entity) {\n return entity.inputEntity\n } else if ('entity' in entity) {\n return getInputPeer(entity.entity)\n } else {\n _raiseCastFail(entity, 'InputPeer')\n }\n }\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf()\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n })\n } else {\n throw new Error('User without accessHash or min info cannot be input')\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty ||\n entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id })\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash\n })\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input')\n }\n }\n if (entity instanceof constructors.ChannelForbidden) {\n // \"channelForbidden are never min\", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash\n })\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty()\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user)\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id })\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId)\n }\n\n _raiseCastFail(entity, 'InputPeer')\n}\n\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n/*CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n/*CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n/*CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return new constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n/*CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped\n }\n const header = Buffer.from(JPEG_HEADER)\n header[164] = stripped[1]\n header[166] = stripped[2]\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER])\n}\n\n/*CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, 'InputFileLocation')\n }\n if (location instanceof constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: '', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128\n }\n if (fileSize <= 786432000) { // 750MB\n return 256\n }\n if (fileSize <= 1572864000) { // 1500MB\n return 512\n }\n\n throw new Error('File size too large')\n}\n\n/*CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/*CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/*CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n/*CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === null || message === undefined) {\n return null\n }\n if (typeof message == 'number') {\n return message\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`)\n}\n\n\n/**\n * Parses the given phone, or returns `None` if it's invalid.\n * @param phone\n */\nfunction parsePhone(phone) {\n return phone.toString().replace(/[+()\\s-]/gm, '')\n}\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n/*CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`\n } else if (entity.firstName) {\n return entity.firstName\n } else if (entity.lastName) {\n return entity.lastName\n } else {\n return ''\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title\n }\n return ''\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n/*CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\nfunction getDC(dcId, cdn = false) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443\n }\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443\n }\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443\n }\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443\n }\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.web.telegram.org',\n port: 443\n }\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`)\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n }*/\n}\n\nmodule.exports = {\n getMessageId,\n //_getEntityPair,\n //getInputMessage,\n //getInputDialog,\n //getInputUser,\n //getInputChannel,\n getInputPeer,\n //parsePhone,\n //parseUsername,\n //getPeer,\n //getPeerId,\n getDisplayName,\n //resolveId,\n //isListLike,\n getAppropriatedPartSize,\n //getInputLocation,\n strippedPhotoToJpg,\n getDC\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumb,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumb),\n count,\n hash,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.')\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`)\n if (typeof alert !== 'undefined') {\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`)\n }\n this.invalidConstructorId = invalidConstructorId\n this.remaining = remaining\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\n */\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`)\n this.checksum = checksum\n this.validChecksum = validChecksum\n }\n}\n\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means \"forgotten/broken authorization key\", while\n */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code = null\n if (payload.length === 4) {\n code = -payload.readInt32LE(0)\n super(`Invalid response buffer (HTTP code ${code})`)\n } else {\n super(`Invalid response buffer (too short ${payload})`)\n }\n this.code = code\n this.payload = payload\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.']\n }\n super(...args)\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.')\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to ' +\n 'synchronize it using msg_id notifications and re-send the original message ' +\n 'with the “correct” msg_id or wrap it in a container with a new msg_id if the ' +\n 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be ' +\n 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id ' +\n 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message ' + '(this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a ' +\n 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower ' +\n 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with ' +\n 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with ' +\n 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n }\n\n constructor(request,code) {\n let errorMessage = BadMessageError.ErrorMessages[code] ||\n `Unknown error code (this should not happen): ${code}.`\n errorMessage+= ` Caused by ${request.className}`\n super(errorMessage)\n this.message = errorMessage\n this.code = code\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n","const { TypeNotFoundError } = require('../errors/Common')\nconst { coreObjects } = require('../tl/core')\nconst { tlobjects } = require('../tl/AllTLObjects')\nconst { readBigIntFromBuffer } = require('../Helpers')\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data\n this._last = null\n this.offset = 0\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0]\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res\n if (signed) {\n res = this.stream.readInt32LE(this.offset)\n } else {\n res = this.stream.readUInt32LE(this.offset)\n }\n this.offset += 4\n return res\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed)\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4).readFloatLE(0)\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been 0) {\n padding = 4 - padding\n this.read(padding)\n }\n\n return data\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes().toString('utf-8')\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false)\n if (value === 0x997275b5) {\n // boolTrue\n return true\n } else if (value === 0xbc799737) {\n // boolFalse\n return false\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`)\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt()\n return new Date(value * 1000)\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false)\n let clazz = tlobjects[constructorId]\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId\n if (value === 0x997275b5) {\n // boolTrue\n return true\n } else if (value === 0xbc799737) {\n // boolFalse\n return false\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = []\n const length = this.readInt()\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject())\n }\n return temp\n }\n\n clazz = coreObjects[constructorId]\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4) // Go back\n const pos = this.tellPosition()\n const error = new TypeNotFoundError(constructorId, this.read())\n this.setPosition(pos)\n throw error\n }\n }\n return clazz.fromReader(this)\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected')\n }\n const count = this.readInt()\n const temp = []\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject())\n }\n return temp\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = null\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[randomId.toString()];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now();\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: update.channelId,\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n const { silent, muteUntil } = update.notifySettings;\n\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n isMuted: silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000),\n },\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000)),\n isShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require(\"./RPCBaseErrors\")\nconst { rpcErrorRe } = require('./RPCErrorList')\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex)\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1]) : null\n return new Cls({ request: request, capture: capture })\n }\n }\n\n return new RPCError(rpcError.errorMessage, request)\n}\n\nmodule.exports = {\n RPCMessageToError,\n ...require('./Common'),\n ...require('./RPCBaseErrors'),\n ...require('./RPCErrorList'),\n}\n","type Scheduler = typeof requestAnimationFrame | typeof onTickEnd | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n requestAnimationFrame(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafCallbacks.unshift(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n return fastRaf(callback, true);\n}\n","const BigInt = require('big-integer')\nconst Factorizator = require('./crypto/Factorizator')\nconst { constructors } = require('./tl')\nconst { readBigIntFromBuffer, readBufferFromBigInt, sha256, bigIntMod, modExp,\n generateRandomBytes } = require('./Helpers')\nconst crypto = require('./crypto/crypto')\nconst SIZE_FOR_HASH = 256\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF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x18, 0xFC, 0x15, 0xE8, 0x3E, 0xBE, 0xA0, 0xF8, 0x7F, 0xA9, 0xFF, 0x5E, 0xED, 0x70, 0x05,\n 0x0D, 0xED, 0x28, 0x49, 0xF4, 0x7B, 0xF9, 0x59, 0xD9, 0x56, 0x85, 0x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 0x6F, 0x4F, 0xAD, 0xF0, 0x34, 0xB1, 0x04, 0x03, 0x11, 0x9C, 0xD8, 0xE3, 0xB9, 0x2F, 0xCC, 0x5B,\n ])\n if (goodPrime.equals(primeBytes)) {\n if ([ 3, 4, 5, 7 ].includes(g)) {\n return // It's good\n }\n }\n throw new Error(\"Changing passwords unsupported\")\n //checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number).greater(BigInt(0))))\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([ Buffer.alloc(SIZE_FOR_HASH - number.length), number ])\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false)\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp)\n\n const minDiffBitsCount = 2048 - 64\n const maxModExpSize = 256\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount ||\n modexp.bitLength() < minDiffBitsCount ||\n Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize)\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length)\n\n for (let i = 0; i < length; i++) {\n a[i] = a[i] ^ b[i]\n }\n\n return a\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512')\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([ algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1 ]))\n const hash2 = await sha256(Buffer.concat([ algo.salt2, hash1, algo.salt2 ]))\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000)\n return sha256(Buffer.concat([ algo.salt2, hash3, algo.salt2 ]))\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g)\n } catch (e) {\n throw new Error('bad p/g in password')\n }\n\n const value = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false))\n return bigNumForHash(value)\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`)\n }\n\n const pwHash = await computeHash(algo, password)\n const p = readBigIntFromBuffer(algo.p, false)\n const g = algo.g\n const B = readBigIntFromBuffer(request.srp_B, false)\n try {\n checkPrimeAndGood(algo.p, g)\n } catch (e) {\n throw new Error('bad /g in password')\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check')\n }\n const x = readBigIntFromBuffer(pwHash, false)\n const pForHash = numBytesForHash(algo.p)\n const gForHash = bigNumForHash(g)\n const bForHash = numBytesForHash(request.srp_B)\n const gX = modExp(BigInt(g), x, p)\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([ pForHash, gForHash ])), false)\n const kgX = bigIntMod(k.multiply(gX),p)\n const generateAndCheckRandom =async () => {\n const randomSize = 256\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize)\n const a = readBigIntFromBuffer(random, false)\n const A = modExp(BigInt(g), a, p)\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A)\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([ aForHash, bForHash ])), false)\n if (u.greater(BigInt(0))) {\n return [ a, aForHash, u ]\n }\n }\n }\n }\n const [ a, aForHash, u ] =await generateAndCheckRandom()\n const gB = bigIntMod(B.subtract(kgX),p)\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error('bad gB')\n }\n\n const ux = u.multiply(x)\n const aUx = a.add(ux)\n const S = modExp(gB, aUx, p)\n const [K, pSha ,gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2)\n ])\n const M1 = await sha256(Buffer.concat([\n xor(pSha,gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]))\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1: M1,\n\n })\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n}\n\n","const utils = require('../Utils')\nconst types = require('../tl').constructors\nconst Session = require('./Abstract')\n\nclass MemorySession extends Session {\n constructor() {\n super()\n\n this._serverAddress = null\n this._dcId = 0\n this._port = null\n this._takeoutId = null\n\n this._entities = new Set()\n this._updateStates = {}\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0\n this._serverAddress = serverAddress\n this._port = port\n }\n\n get dcId() {\n return this._dcId\n }\n\n get serverAddress() {\n return this._serverAddress\n }\n\n get port() {\n return this._port\n }\n\n get authKey() {\n return this._authKey\n }\n\n set authKey(value) {\n this._authKey = value\n }\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n }*/\n}\n\nmodule.exports = MemorySession\n","const { serializeBytes } = require('../index')\nconst { inflate } = require('pako/dist/pako_inflate')\n//CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1\n static classType = 'constructor'\n\n constructor(data) {\n this.data = data\n this.CONSTRUCTOR_ID = 0x3072cfa1\n this.classType = 'constructor'\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes()\n if (gzipped.length < data.length) {\n return gzipped\n }\n }\n return data\n }\n\n static gzip(input) {\n return Buffer.from(input)\n // TODO this usually makes it faster for large requests\n //return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input))\n }\n\n async toBytes() {\n const g = Buffer.alloc(4)\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0)\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ])\n }\n\n static async read(reader) {\n const constructor = reader.readInt(false)\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal')\n }\n return await GZIPPacked.gzip(reader.tgReadBytes())\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()))\n }\n}\n\nmodule.exports = GZIPPacked\n","const { sha1, toSignedLittleBuffer,readBufferFromBigInt, readBigIntFromBuffer } = require('../Helpers')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { sleep } = require('../Helpers')\n\nclass AuthKey {\n\n constructor(value, hash) {\n if (!hash || !value) {\n return\n }\n this._key = value\n this._hash = hash\n const reader = new BinaryReader(hash)\n this.auxHash = reader.readLong(false)\n reader.read(4)\n this.keyId = reader.readLong(false)\n }\n\n async setKey(value) {\n if (!value) {\n this._key = this.auxHash = this.keyId = this._hash = null\n return\n }\n if (value instanceof AuthKey) {\n this._key = value._key\n this.auxHash = value.auxHash\n this.keyId = value.keyId\n this._hash = value._hash\n return\n }\n this._key = value\n this._hash = await sha1(this._key)\n const reader = new BinaryReader(this._hash)\n this.auxHash = reader.readLong(false)\n reader.read(4)\n this.keyId = reader.readLong(false)\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await sleep(20)\n }\n }\n\n getKey() {\n return this._key\n }\n\n // TODO : This doesn't really fit here, it's only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields' values\n * @param newNonce\n * @param number\n * @returns {bigint}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32)\n const n = Buffer.alloc(1)\n n.writeUInt8(number, 0)\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])])\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20)\n return readBigIntFromBuffer(shaData, true, true)\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey().equals(this._key)\n }\n}\n\nmodule.exports = AuthKey\n","const Logger = require('./Logger')\nconst BinaryWriter = require('./BinaryWriter')\nconst BinaryReader = require('./BinaryReader')\nconst PromisedWebSockets = require('./PromisedWebSockets')\nconst MessagePacker = require('./MessagePacker')\nconst AsyncQueue = require('./AsyncQueue')\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","const AES = require('@cryptography/aes').default;\nconst { i2ab, ab2i } = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue)\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes)\n this._counter = bytes\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0\n } else {\n this._counter[i]++\n break\n }\n }\n }\n}\n\nclass CTR {\n constructor(key, counter) {\n\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter)\n }\n\n this._counter = counter\n\n this._remainingCounter = null\n this._remainingCounterIndex = 16\n\n this._aes = new AES(getWords(key))\n }\n\n update(plainText) {\n return this.encrypt(plainText)\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText)\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))))\n this._remainingCounterIndex = 0\n this._counter.increment()\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++]\n }\n\n return encrypted\n }\n}\n\n// endregion\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv)\n }\n}\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv)\n }\n}\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count)\n crypto.getRandomValues(bytes)\n return bytes\n}\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm\n }\n\n update(data) {\n //We shouldn't be needing new Uint8Array but it doesn't\n //work without it\n this.data = new Uint8Array(data)\n }\n\n async digest() {\n if (this.algorithm === 'sha1') {\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data))\n } else if (this.algorithm === 'sha256') {\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data))\n }\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n {name: 'PBKDF2'}, false, ['deriveBits'])\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512', salt, iterations\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm)\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2\n}\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = null) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request))\n )\n this.code = code\n this.message = message\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`\n } else {\n return ''\n }\n }\n}\n\n/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code)\n this.code = code || 303\n this.message = message || 'ERROR_SEE_OTHER'\n }\n}\n\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\nclass BadRequestError extends RPCError {\n code = 400\n message = 'BAD_REQUEST'\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401\n message = 'UNAUTHORIZED'\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403\n message = 'FORBIDDEN'\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404\n message = 'NOT_FOUND'\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406\n message = 'AUTH_KEY'\n}\n\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\nclass FloodError extends RPCError {\n code = 420\n message = 'FLOOD'\n}\n\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\nclass ServerError extends RPCError {\n code = 500 // Also witnessed as -500\n message = 'INTERNAL'\n}\n\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this \"special\" RPCError.\n */\nclass TimedOutError extends RPCError {\n code = 503 // Only witnessed as -503\n message = 'Timeout'\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n}\n","\nclass TLMessage {\n static SIZE_OVERHEAD = 12;\n static classType = \"constructor\"\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId\n this.seqNo = seqNo\n this.obj = obj\n this.classType = \"constructor\"\n }\n}\n\nmodule.exports = TLMessage\n","const TLMessage = require('./TLMessage')\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n static classType = \"constructor\"\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n\n this.CONSTRUCTOR_ID = 0x73f1f8dc\n this.messages = messages\n this.classType = \"constructor\"\n }\n\n static async fromReader(reader) {\n const messages = []\n const length = reader.readInt()\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong()\n const seqNo = reader.readInt()\n const length = reader.readInt()\n const before = reader.tellPosition()\n const obj = reader.tgReadObject()\n reader.setPosition(before + length)\n const tlMessage = new TLMessage(msgId, seqNo, obj)\n messages.push(tlMessage)\n }\n return new MessageContainer(messages)\n }\n}\n\nmodule.exports = MessageContainer\n","const MTProtoPlainSender = require('./MTProtoPlainSender')\nconst doAuthentication = require('./Authenticator')\nconst MTProtoSender = require('./MTProtoSender')\n\nclass UpdateConnectionState {\n static disconnected = -1\n static connected = 1\n static broken = 0\n\n constructor(state) {\n this.state = state\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection')\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n}\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets')\nconst AsyncQueue = require('../../extensions/AsyncQueue')\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = null\n\n constructor(ip, port, dcId, loggers) {\n this._ip = ip\n this._port = port\n this._dcId = dcId\n this._log = loggers\n this._connected = false\n this._sendTask = null\n this._recvTask = null\n this._codec = null\n this._obfuscation = null // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue()\n this._recvArray = new AsyncQueue()\n //this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets()\n }\n\n async _connect() {\n this._log.debug('Connecting')\n this._codec = new this.PacketCodecClass(this)\n await this.socket.connect(this._port, this._ip, this)\n this._log.debug('Finished connecting')\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn()\n }\n\n async connect() {\n await this._connect()\n this._connected = true\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop()\n }\n this._recvTask = this._recvLoop()\n }\n\n async disconnect() {\n this._connected = false\n await this._recvArray.push(null)\n await this.socket.close()\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected')\n }\n await this._sendArray.push(data)\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop()\n // null = sentinel value = keep trying\n if (result) {\n return result\n }\n }\n throw new Error('Not connected')\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop()\n if (!data) {\n this._sendTask = null\n return\n }\n await this._send(data)\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending')\n }\n }\n\n async _recvLoop() {\n let data\n while (this._connected) {\n try {\n data = await this._recv()\n if (!data) {\n throw new Error(\"no data received\")\n }\n } catch (e) {\n this._log.info('connection closed')\n //await this._recvArray.push()\n\n this.disconnect()\n return\n }\n await this._recvArray.push(data)\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag)\n }\n }\n\n async _send(data) {\n const encodedPacket = this._codec.encodePacket(data)\n this.socket.write(encodedPacket)\n }\n\n async _recv() {\n return await this._codec.readPacket(this.socket)\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = null\n\n async _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this)\n this.socket.write(this._obfuscation.header)\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data))\n }\n\n\n async _recv() {\n return await this._codec.readPacket(this._obfuscation)\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection\n }\n\n encodePacket(data) {\n throw new Error('Not Implemented')\n\n // Override\n }\n\n async readPacket(reader) {\n // override\n throw new Error('Not Implemented')\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n}\n","const MemorySession = require('./Memory')\nconst AuthKey = require('../crypto/AuthKey')\nconst utils = require('../Utils')\n\nconst STORAGE_KEY_BASE = 'GramJs-session-'\n\nclass StorageSession extends MemorySession {\n constructor(sessionId) {\n super()\n this._storageKey = sessionId\n this._authKeys = {}\n }\n\n async load() {\n if (!this._storageKey) {\n return\n }\n\n try {\n const json = await this._fetchFromCache()\n const { mainDcId, keys, hashes } = JSON.parse(json)\n const { ipAddress, port } = utils.getDC(mainDcId)\n\n this.setDC(mainDcId, ipAddress, port, true)\n\n Object.keys(keys).forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]){\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data)\n )\n }\n })\n } catch (err) {\n console.warn('Failed to retrieve or parse session from storage')\n console.warn(err)\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId\n this._serverAddress = serverAddress\n this._port = port\n\n delete this._authKeys[dcId]\n\n if (!skipUpdateStorage) {\n void this._updateStorage()\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey()\n }\n\n await this._updateStorage()\n\n return this._storageKey\n }\n\n get authKey() {\n throw new Error('Not supported')\n }\n\n set authKey(value) {\n throw new Error('Not supported')\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId]\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey\n\n void this._updateStorage()\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return\n }\n\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {}\n }\n\n Object.keys(this._authKeys).map((dcId) => {\n const authKey = this._authKeys[dcId]\n sessionData.keys[dcId] = authKey._key\n sessionData.hashes[dcId] = authKey._hash\n })\n\n try {\n await this._saveToCache(JSON.stringify(sessionData))\n } catch (err) {\n console.warn('Failed to update session in storage')\n console.warn(err)\n }\n }\n\n async delete() {\n try {\n return await this._delete()\n } catch (err) {\n console.warn('Failed to delete session from storage')\n console.warn(err)\n }\n }\n\n // @abstract\n async _delete() {\n throw new Error('Not Implemented')\n }\n\n // @abstract\n async _fetchFromCache() {\n throw new Error('Not Implemented')\n }\n\n // @abstract\n async _saveToCache(data) {\n throw new Error('Not Implemented')\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`\n}\n\nmodule.exports = StorageSession\n","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase())\n return result.replace(/_/g, '')\n}\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', '')\n)\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc // null#56730bcc = Null;\n])\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1 // gzip_packed\n])\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c\n const crcTable = []\n for (let n = 0; n < 256; n++) {\n c = n\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1))\n }\n crcTable[n] = c\n }\n return crcTable\n}\n\nlet crcTable = null\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable()\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf)\n }\n let crc = -1\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index]\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8)\n }\n return (crc ^ (-1)) >>> 0\n}\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/)\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`)\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line)\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction: isFunction,\n namespace: null\n }\n if (!currentConfig.constructorId) {\n\n let hexId = ''\n let args\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig).map((arg) => arg.toString()).join(' ')}`\n } else {\n args = ''\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '')\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'))\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType)\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/)\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name)\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n }*/\n return currentConfig\n}\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: null,\n useVectorId: null\n }\n\n // Special case: some types can be inferred, which makes it\n // less annoying to type. Currently the only type that can\n // be inferred is if the name is 'random_id', to which a\n // random ID will be assigned if left as None (the default)\n let canBeInferred = name === 'random_id'\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '')\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/)\n\n if (flagMatch) {\n currentConfig.isFlag = true\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/)\n\n if (vectorMatch) {\n currentConfig.isVector = true\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0)\n )\n ) {\n currentConfig.skipConstructorId = true\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig\n}\n\n\nconst parseTl = function* (content, layer, methods = [], ignoreIds = CORE_TYPES) {\n const methodInfo = (methods || []).reduce((o, m) => ({ ...o, [m.name]: m }), {})\n const objAll = []\n const objByName = {}\n const objByType = {}\n\n const file = content\n\n let isFunction = false\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//')\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex)\n }\n\n line = line.trim()\n\n if (!line) {\n continue\n }\n\n const match = line.match(/---(\\w+)---/)\n\n if (match) {\n const [, followingTypes] = match\n isFunction = followingTypes === 'functions'\n continue\n }\n\n try {\n const result = fromLine(line, isFunction)\n\n if (ignoreIds.has(result.constructorId)) {\n continue\n }\n\n objAll.push(result)\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = []\n }\n\n objByName[result.name] = result\n objByType[result.result].push(result)\n }\n } catch (e) {\n if (!e.toString().includes('vector#1cb5c415')) {\n throw e\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n //console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes'\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj\n }\n\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes(`g`)) {\n regex = new RegExp(regex.source, `g`)\n }\n\n const res = regex.exec(str)\n\n if (res) {\n matches.push(res.slice(1))\n findAll(regex, str, matches)\n }\n\n return matches\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data == 'string') {\n data = Buffer.from(data)\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`)\n }\n }\n const r = []\n let padding\n if (data.length < 254) {\n padding = (data.length + 1) % 4\n if (padding !== 0) {\n padding = 4 - padding\n }\n r.push(Buffer.from([data.length]))\n r.push(data)\n } else {\n padding = data.length % 4\n if (padding !== 0) {\n padding = 4 - padding\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]))\n r.push(data)\n }\n r.push(Buffer.alloc(padding)\n .fill(0))\n\n return Buffer.concat(r)\n\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0)\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000)\n }\n if (typeof dt == 'number') {\n const t = Buffer.alloc(4)\n t.writeInt32LE(dt, 0)\n return t\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`)\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase\n}\n","var S = new Uint8Array(256);\nvar Si = new Uint8Array(256);\nvar T1 = new Uint32Array(256);\nvar T2 = new Uint32Array(256);\nvar T3 = new Uint32Array(256);\nvar T4 = new Uint32Array(256);\nvar T5 = new Uint32Array(256);\nvar T6 = new Uint32Array(256);\nvar T7 = new Uint32Array(256);\nvar T8 = new Uint32Array(256);\nfunction computeTables() {\n var d = new Uint8Array(256);\n var t = new Uint8Array(256);\n var x2;\n var x4;\n var x8;\n var s;\n var tEnc;\n var tDec;\n var x = 0;\n var xInv = 0;\n // Compute double and third tables\n for (var i = 0; i < 256; i++) {\n d[i] = i << 1 ^ (i >> 7) * 283;\n t[d[i] ^ i] = i;\n }\n for (; !S[x]; x ^= x2 || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n S[x] = s;\n Si[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n T1[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T2[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T3[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T4[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T5[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T6[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T7[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T8[s] = tDec = tDec << 24 ^ tDec >>> 8;\n xInv = t[xInv] || 1;\n }\n}\n\n/**\n * Gets a uint32 from string in big-endian order order\n */\nfunction s2i(str, pos) {\n return (str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3));\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Helper function for transforming string key to Uint32Array\n */\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n if (typeof key === 'string') {\n if (key.length % 4 !== 0)\n for (var i = key.length % 4; i <= 4; i++)\n key += '\\0x00';\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4)\n buf[i / 4] = s2i(key, i);\n return buf;\n }\n if (key instanceof Uint8Array) {\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4) {\n buf[i / 4] = (key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]);\n }\n return buf;\n }\n throw new Error('Unable to create 32-bit words');\n}\nfunction xor(left, right, to) {\n if (to === void 0) { to = left; }\n for (var i = 0; i < left.length; i++)\n to[i] = left[i] ^ right[i];\n}\n\ncomputeTables();\n/**\n * Low-level AES Cipher\n */\nvar AES = /** @class */ (function () {\n function AES(_key) {\n var key = getWords(_key);\n if (key.length !== 4 && key.length !== 6 && key.length !== 8) {\n throw new Error('Invalid key size');\n }\n this.encKey = new Uint32Array(4 * key.length + 28);\n this.decKey = new Uint32Array(4 * key.length + 28);\n this.encKey.set(key);\n var rcon = 1;\n var i = key.length;\n var tmp;\n // schedule encryption keys\n for (; i < 4 * key.length + 28; i++) {\n tmp = this.encKey[i - 1];\n // apply sbox\n if (i % key.length === 0 || (key.length === 8 && i % key.length === 4)) {\n tmp = S[tmp >>> 24] << 24 ^ S[(tmp >> 16) & 255] << 16 ^ S[(tmp >> 8) & 255] << 8 ^ S[tmp & 255];\n // shift rows and add rcon\n if (i % key.length === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ (rcon << 24);\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n this.encKey[i] = this.encKey[i - key.length] ^ tmp;\n }\n // schedule decryption keys\n for (var j = 0; i; j++, i--) {\n tmp = this.encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n this.decKey[j] = tmp;\n }\n else {\n this.decKey[j] = (T5[S[tmp >>> 24]]\n ^ T6[S[(tmp >> 16) & 255]]\n ^ T7[S[(tmp >> 8) & 255]]\n ^ T8[S[tmp & 255]]);\n }\n }\n }\n AES.prototype.encrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.encKey[0];\n var b = message[1] ^ this.encKey[1];\n var c = message[2] ^ this.encKey[2];\n var d = message[3] ^ this.encKey[3];\n var rounds = this.encKey.length / 4 - 2;\n var k = 4;\n var a2;\n var b2;\n var c2;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T1[a >>> 24] ^ T2[(b >> 16) & 255] ^ T3[(c >> 8) & 255] ^ T4[d & 255] ^ this.encKey[k];\n b2 = T1[b >>> 24] ^ T2[(c >> 16) & 255] ^ T3[(d >> 8) & 255] ^ T4[a & 255] ^ this.encKey[k + 1];\n c2 = T1[c >>> 24] ^ T2[(d >> 16) & 255] ^ T3[(a >> 8) & 255] ^ T4[b & 255] ^ this.encKey[k + 2];\n d = T1[d >>> 24] ^ T2[(a >> 16) & 255] ^ T3[(b >> 8) & 255] ^ T4[c & 255] ^ this.encKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n // console.log(a, b, c, d);\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[i] = (S[a >>> 24] << 24\n ^ S[(b >> 16) & 255] << 16\n ^ S[(c >> 8) & 255] << 8\n ^ S[d & 255]\n ^ this.encKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n AES.prototype.decrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.decKey[0];\n var b = message[3] ^ this.decKey[1];\n var c = message[2] ^ this.decKey[2];\n var d = message[1] ^ this.decKey[3];\n var rounds = this.decKey.length / 4 - 2;\n var a2;\n var b2;\n var c2;\n var k = 4;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T5[a >>> 24] ^ T6[(b >> 16) & 255] ^ T7[(c >> 8) & 255] ^ T8[d & 255] ^ this.decKey[k];\n b2 = T5[b >>> 24] ^ T6[(c >> 16) & 255] ^ T7[(d >> 8) & 255] ^ T8[a & 255] ^ this.decKey[k + 1];\n c2 = T5[c >>> 24] ^ T6[(d >> 16) & 255] ^ T7[(a >> 8) & 255] ^ T8[b & 255] ^ this.decKey[k + 2];\n d = T5[d >>> 24] ^ T6[(a >> 16) & 255] ^ T7[(b >> 8) & 255] ^ T8[c & 255] ^ this.decKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[3 & -i] = (Si[a >>> 24] << 24\n ^ Si[(b >> 16) & 255] << 16\n ^ Si[(c >> 8) & 255] << 8\n ^ Si[d & 255]\n ^ this.decKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n return AES;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE = /** @class */ (function () {\n function AES_IGE(key, iv, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.key = getWords(key);\n this.iv = getWords(iv);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var prevX = this.iv.subarray(this.blockSize, this.iv.length);\n var prevY = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = text.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.encrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n cipherText[j] = y[k];\n }\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n var cipherText = getWords(message);\n var text = buf || new Uint32Array(cipherText.length);\n var prevY = this.iv.subarray(this.blockSize, this.iv.length);\n var prevX = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = cipherText.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.decrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n text[j] = y[k];\n }\n return text;\n };\n return AES_IGE;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE$1 = /** @class */ (function () {\n function AES_IGE(key, counter, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.offset = 0;\n this.key = getWords(key);\n this.counter = getWords(counter);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n if (this.counter.length !== 4) {\n throw new Error('AES-CTR mode counter must be 16 bytes length');\n }\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var offset = this.offset;\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = this.cipher.encrypt(this.counter);\n for (var j = i, k = offset; j < text.length && k < this.blockSize; j++, k++)\n cipherText[j] = x[k] ^ text[j];\n if (text.length - i >= this.blockSize)\n this.incrementCounter();\n if (offset) {\n i -= offset;\n offset = 0;\n }\n }\n this.offset = (this.offset + (text.length % 4)) % 4;\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n return this.encrypt(message, buf);\n };\n AES_IGE.prototype.incrementCounter = function () {\n // increment counter\n for (var carry = this.counter.length - 1; carry >= 0; carry--) {\n if (++this.counter[carry] < 0xFFFFFFFF)\n break; // If overflowing, it'll be 0 and we'll have to continue propagating the carry\n }\n };\n return AES_IGE;\n}());\n\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\n","let _level = null\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug']\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug'\n }\n\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n if (!this.isBrowser) {\n this.colors = {\n start: '\\x1b[2m',\n warn: '\\x1b[35m',\n info: '\\x1b[33m',\n debug: '\\x1b[36m',\n error: '\\x1b[31m',\n end: '\\x1b[0m',\n }\n } else {\n this.colors = {\n start: '%c',\n warn: 'color : #ff00ff',\n info: 'color : #ffff00',\n debug: 'color : #00ffff',\n error: 'color : #ff0000',\n end: '',\n }\n }\n this.messageFormat = '[%t] [%l] - [%m]'\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level))\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n this._log('warn', message, this.colors.warn)\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info)\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug)\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n this._log('error', message, this.colors.error)\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message)\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level){\n return\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n console.log(color + this.format(message, level) + this.colors.end)\n } else {\n console.log(this.colors.start + this.format(message, level), color)\n }\n } else {\n\n }\n }\n}\n\nmodule.exports = Logger\n","const { RPCError, InvalidDCError, FloodError, BadRequestError } = require('./RPCBaseErrors')\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0)\n super(`Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request))\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request)\n this.codeLength = codeLength\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n]\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n EmailUnconfirmedError\n}\n","class Session {\n constructor() {\n\n }\n\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n }*/\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented')\n }\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /*CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /*CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /*CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /*CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n /*CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /*CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /*CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /*CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer])\n }\n\n getValue() {\n return this._stream\n }\n}\n\nmodule.exports = BinaryWriter\n","const TLMessage = require('./TLMessage')\nconst RPCResult = require('./RPCResult')\nconst MessageContainer = require('./MessageContainer')\nconst GZIPPacked = require('./GZIPPacked')\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n}\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n}\n","const { RpcError } = require('../index').constructors\nconst GZIPPacked = require('./GZIPPacked')\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n static classType = \"constructor\"\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01\n this.reqMsgId = reqMsgId\n this.body = body\n this.error = error\n this.classType = \"constructor\"\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong()\n const innerCode = reader.readInt(false)\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, null, RpcError.fromReader(reader))\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data)\n }\n reader.seek(-4)\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), null)\n }\n}\n\nmodule.exports = RPCResult\n","const api = require('./api')\nconst LAYER = 121\nconst tlobjects = {}\n\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects\n}\n","const Mutex = require('async-mutex').Mutex\nconst mutex = new Mutex()\n\nconst WebSocketClient = require('websocket').w3cwebsocket\n\nconst closeError = new Error('WebSocket was closed')\n\nclass PromisedWebSockets {\n constructor() {\n /*CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = null\n this.closed = true\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0)\n while (true) {\n const thisTime = await this.read(number)\n readData = Buffer.concat([readData, thisTime])\n number = number - thisTime.length\n if (!number) {\n return readData\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError\n }\n await this.canRead\n if (this.closed) {\n throw closeError\n }\n const toReturn = this.stream.slice(0, number)\n this.stream = this.stream.slice(number)\n if (this.stream.length === 0) {\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n }\n\n return toReturn\n }\n\n async readAll() {\n if (this.closed || !await this.canRead) {\n throw closeError\n }\n const toReturn = this.stream\n this.stream = Buffer.alloc(0)\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n\n return toReturn\n }\n\n getWebSocketLink(ip, port) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`\n } else {\n return `ws://${ip}:${port}/apiws`\n }\n }\n\n async connect(port, ip) {\n this.stream = Buffer.alloc(0)\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n this.closed = false\n this.website = this.getWebSocketLink(ip, port)\n this.client = new WebSocketClient(this.website, 'binary')\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive()\n resolve(this)\n }\n this.client.onerror = (error) => {\n reject(error)\n }\n this.client.onclose = () => {\n this.resolveRead(false)\n this.closed = true\n }\n //CONTEST\n // Seems to not be working, at least in a web worker\n self.addEventListener('offline', async () => {\n await this.close()\n this.resolveRead(false)\n })\n })\n }\n\n write(data) {\n if (this.closed) {\n throw closeError\n }\n this.client.send(data)\n }\n\n async close() {\n await this.client.close()\n this.closed = true\n }\n\n async receive() {\n this.client.onmessage = async (message) => {\n const release = await mutex.acquire()\n try {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer())\n this.stream = Buffer.concat([this.stream, data])\n this.resolveRead(true)\n } finally {\n release()\n }\n }\n }\n}\n\nmodule.exports = PromisedWebSockets\n","const MessageContainer = require('../tl/core/MessageContainer')\nconst TLMessage = require('../tl/core/TLMessage')\nconst BinaryWriter = require('../extensions/BinaryWriter')\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state\n this._queue = []\n this._pendingStates = []\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve\n }))\n this._log = logger\n }\n\n values() {\n return this._queue\n }\n\n append(state) {\n this._queue.push(state)\n this.setReady(true)\n\n if (state) {\n this._pendingStates.push(state)\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {})\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state)\n })\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state)\n }\n this.setReady(true)\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve\n }))\n await this._ready\n }\n if (!this._queue[this._queue.length - 1]) {\n this._queue = []\n return\n }\n let data\n let buffer = new BinaryWriter(Buffer.alloc(0))\n\n const batch = []\n let size = 0\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift()\n size += state.data.length + TLMessage.SIZE_OVERHEAD\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId\n if (state.after) {\n afterId = state.after.msgId\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n )\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className || state.request.constructor.name}`)\n batch.push(state)\n continue\n }\n if (batch.length) {\n this._queue.unshift(state)\n break\n }\n this._log.warn(`Message payload for ${state.request.className || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`)\n state.reject('Request Payload is too big')\n size = 0\n continue\n }\n if (!batch.length) {\n return null\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8)\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0)\n b.writeInt32LE(batch.length, 4)\n data = Buffer.concat([b, buffer.getValue()])\n buffer = new BinaryWriter(Buffer.alloc(0))\n const containerId = await this._state.writeDataAsMessage(\n buffer, data, false,\n )\n for (const s of batch) {\n s.containerId = containerId\n }\n }\n\n data = buffer.getValue()\n return { batch, data }\n }\n\n rejectAll() {\n this._pendingStates.forEach((requestState) => {\n requestState.reject(new Error('Disconnect'))\n })\n }\n}\n\nmodule.exports = MessagePacker\n","class AsyncQueue {\n constructor() {\n this._queue = []\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve\n })\n this.canPush = true\n }\n\n async push(value) {\n await this.canPush\n this._queue.push(value)\n this.resolveGet(true)\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve\n })\n }\n\n async pop() {\n await this.canGet\n const returned = this._queue.pop()\n this.resolvePush(true)\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve\n })\n return returned\n }\n}\n\nmodule.exports = AsyncQueue\n","const MtProtoPlainSender = require('./MTProtoPlainSender')\nconst MTProtoState = require('./MTProtoState')\nconst Helpers = require('../Helpers')\nconst AuthKey = require('../crypto/AuthKey')\nconst doAuthentication = require('./Authenticator')\nconst RPCResult = require('../tl/core/RPCResult')\nconst MessageContainer = require('../tl/core/MessageContainer')\nconst GZIPPacked = require('../tl/core/GZIPPacked')\nconst RequestState = require('./RequestState')\nconst { MsgsAck, upload, MsgsStateInfo, Pong } = require('../tl').constructors\nconst MessagePacker = require('../extensions/MessagePacker')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { UpdateConnectionState } = require(\"./index\");\nconst { BadMessageError } = require(\"../errors/Common\")\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors\nconst { SecurityError } = require('../errors/Common')\nconst { InvalidBufferError } = require('../errors/Common')\nconst { LogOut } = require('../tl').requests.auth\nconst { RPCMessageToError } = require('../errors')\nconst { TypeNotFoundError } = require('../errors/Common')\n\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: null,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: null,\n authKeyCallback: null,\n updateCallback: null,\n autoReconnectCallback: null,\n isMainSender: null,\n onConnectionBreak: null,\n }\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts }\n this._connection = null\n this._log = args.logger\n this._dcId = args.dcId\n this._retries = args.retries\n this._delay = args.delay\n this._autoReconnect = args.autoReconnect\n this._connectTimeout = args.connectTimeout\n this._authKeyCallback = args.authKeyCallback\n this._updateCallback = args.updateCallback\n this._autoReconnectCallback = args.autoReconnectCallback\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false\n this._reconnecting = false\n this._disconnected = true\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = null\n this._recv_loop_handle = null\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey()\n this._state = new MTProtoState(this.authKey, this._log)\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log)\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {}\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set()\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = []\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n }\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!')\n return false\n }\n this._connection = connection\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect()\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected))\n }\n break\n } catch (err) {\n if (this._updateCallback && attempt===0){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected))\n }\n this._log.error('WebSocket connection failed attempt: ' + (attempt + 1))\n await Helpers.sleep(this._delay)\n }\n }\n }\n\n isConnected() {\n return this._user_connected\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n await this._disconnect()\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected')\n }\n //CONTEST\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n }*/\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection))\n await this._connection.connect()\n this._log.debug('Connection success!')\n //process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log)\n this._log.debug('New auth_key attempt ...')\n const res = await doAuthentication(plain, this._log)\n this._log.debug('Generated new auth_key successfully')\n await this.authKey.setKey(res.authKey)\n\n this._state.time_offset = res.timeOffset\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId)\n }\n } else {\n this._log.debug('Already have an auth key ...')\n }\n this._user_connected = true\n this._reconnecting = false\n\n this._log.debug('Starting send loop')\n this._send_loop_handle = this._sendLoop()\n\n this._log.debug('Starting receive loop')\n this._recv_loop_handle = this._recvLoop()\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()))\n }\n\n async _disconnect(error = null) {\n this._send_queue.rejectAll()\n\n if (this._connection === null) {\n this._log.info('Not disconnecting (already have no connection)')\n return\n }\n if (this._updateCallback){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected))\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()))\n this._user_connected = false\n this._log.debug('Closing current connection...')\n await this._connection.disconnect()\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log)\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }))\n this._send_queue.append(ack)\n this._last_acks.push(ack)\n this._pending_ack.clear()\n }\n this._log.debug('Waiting for messages to send...'+this._reconnecting)\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get()\n\n if (this._reconnecting) {\n return\n }\n\n if (!res) {\n continue\n }\n let data = res.data\n const batch = res.batch\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`)\n\n data = await this._state.encryptMessageData(data)\n\n try {\n await this._connection.send(data)\n } catch (e) {\n this._log.error(e)\n this._log.info('Connection closed while sending data')\n return\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent')\n }\n }\n\n async _recvLoop() {\n let body\n let message\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...')\n try {\n body = await this._connection.recv()\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data')\n this.reconnect()\n return\n }\n try {\n message = await this._state.decryptMessageData(body)\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`)\n continue\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`)\n continue\n } else if (e instanceof InvalidBufferError) {\n this._log.info('Broken authorization key; resetting')\n if (this._updateCallback && this._isMainSender){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken))\n } else if (this._onConnectionBreak && !this._isMainSender){\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId)\n }\n\n // We don't really need to do this if we're going to sign in again\n /*await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n }*/\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return\n } else {\n this._log.error('Unhandled error while receiving data')\n this._log.error(e)\n this.reconnect()\n return\n }\n }\n try {\n await this._processMessage(message)\n } catch (e) {\n this._log.error('Unhandled error while receiving data')\n this._log.error(e)\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId)\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID]\n if (!handler) {\n handler = this._handleUpdate.bind(this)\n }\n\n await handler(message)\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId]\n if (state) {\n delete this._pending_state[msgId]\n return [state]\n }\n\n const toPop = []\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId)\n }\n }\n\n if (toPop.length) {\n const temp = []\n for (const x of toPop) {\n temp.push(this._pending_state[x])\n delete this._pending_state[x]\n }\n return temp\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack]\n }\n }\n\n return []\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const RPCResult = message.obj\n const state = this._pending_state[RPCResult.reqMsgId]\n if (state) {\n delete this._pending_state[RPCResult.reqMsgId]\n }\n this._log.debug(`Handling RPC result for message ${RPCResult.reqMsgId}`)\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(RPCResult.body)\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File')\n }\n } catch (e) {\n this._log.error(e)\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${RPCResult.body}`)\n return\n } else {\n throw e\n }\n }\n }\n if (RPCResult.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(RPCResult.error, state.request)\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })))\n state.reject(error)\n } else {\n const reader = new BinaryReader(RPCResult.body)\n const read = state.request.readResult(reader)\n state.resolve(read)\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container')\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage)\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data')\n const reader = new BinaryReader(message.obj.data)\n message.obj = reader.tgReadObject()\n await this._processMessage(message)\n }\n\n async _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`)\n return\n }\n this._log.debug('Handling update ' + message.obj.className)\n if (this._updateCallback) {\n this._updateCallback(message.obj)\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handlePong(message) {\n const pong = message.obj\n this._log.debug(`Handling pong for message ${pong.msgId}`)\n const state = this._pending_state[pong.msgId]\n delete this._pending_state[pong.msgId]\n\n // Todo Check result\n if (state) {\n state.resolve(pong)\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleBadServerSalt(message) {\n const badSalt = message.obj\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`)\n this._state.salt = badSalt.newServerSalt\n const states = this._popStates(badSalt.badMsgId)\n this._send_queue.extend(states)\n this._log.debug(`${states.length} message(s) will be resent`)\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleBadNotification(message) {\n const badMsg = message.obj\n const states = this._popStates(badMsg.badMsgId)\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`)\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const to = this._state.updateTimeOffset(message.msgId)\n this._log.info(`System clock is wrong, set time offset to ${to}s`)\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16\n } else {\n\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode))\n }\n\n return\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states)\n this._log.debug(`${states.length} messages will be resent due to bad msg`)\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId\n this._log.debug(`Handling detailed info for message ${msgId}`)\n this._pending_ack.add(msgId)\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId\n this._log.debug(`Handling new detailed info for message ${msgId}`)\n this._pending_ack.add(msgId)\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created')\n this._state.salt = message.obj.serverSalt\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleAck(message) {\n const ack = message.obj\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`)\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId]\n if (state && state.request instanceof LogOut) {\n delete this._pending_state[msgId]\n state.resolve(true)\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`)\n const state = this._pending_state[message.msgId]\n\n if (state) {\n delete this._pending_state[message]\n state.resolve(message.obj)\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1).repeat(message.obj.msgIds))),\n )\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleMsgAll(message) {\n }\n\n async reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info(\"Started reconnecting\")\n this._reconnect()\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...')\n try {\n await this.disconnect()\n } catch (err) {\n this._log.warn(err)\n }\n\n this._send_queue.append(null)\n this._state.reset()\n\n await this.connect(this._connection, true)\n\n this._reconnecting = false\n // uncomment this if you want to resend\n //this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {}\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback()\n }\n }\n}\n\nmodule.exports = MTProtoSender\n","/**\n * This module contains the class used to communicate with Telegram's servers\n * in plain text, when no authorization key has been created yet.\n */\nconst Helpers = require('../Helpers')\nconst MTProtoState = require('./MTProtoState')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { InvalidBufferError } = require('../errors/Common')\nconst BigInt = require('big-integer')\nconst { toSignedLittleBuffer } = require(\"../Helpers\")\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState(connection, loggers)\n this._connection = connection\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n\n let body = request.getBytes()\n let msgId = this._state._getNewMsgId()\n const m = toSignedLittleBuffer(msgId, 8)\n const b = Buffer.alloc(4)\n b.writeInt32LE(body.length, 0)\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body])\n\n await this._connection.send(res)\n body = await this._connection.recv()\n if (body.length < 8) {\n throw new InvalidBufferError(body)\n }\n const reader = new BinaryReader(body)\n const authKeyId = reader.readLong()\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId')\n }\n msgId = reader.readLong()\n if (msgId.eq(BigInt(0))) {\n throw new Error('Bad msgId')\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n const length = reader.readInt()\n if (length <= 0) {\n throw new Error('Bad length')\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn't used for anything else after this, it's unnecessary.\n */\n return reader.tgReadObject()\n }\n\n}\n\nmodule.exports = MTProtoPlainSender\n","const Helpers = require('../Helpers')\nconst IGE = require('../crypto/IGE')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst GZIPPacked = require('../tl/core/GZIPPacked')\nconst { TLMessage } = require('../tl/core')\nconst { SecurityError, InvalidBufferError } = require('../errors/Common')\nconst { InvokeAfterMsg } = require('../tl').requests\nconst BigInt = require('big-integer')\nconst { toSignedLittleBuffer,readBufferFromBigInt } = require(\"../Helpers\")\nconst { readBigIntFromBuffer } = require(\"../Helpers\")\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey\n this._log = loggers\n this.timeOffset = 0\n this.salt = 0\n\n this.id = this._sequence = this._lastMsgId = null\n this.reset()\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true)\n this._sequence = 0\n this._lastMsgId = BigInt(0)\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId()\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha256a , sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey]))\n ])\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)])\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)])\n return { key, iv }\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId()\n const seqNo = this._getSeqNo(contentRelated)\n let body\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data)\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes())\n }\n const s = Buffer.alloc(4)\n s.writeInt32LE(seqNo, 0)\n const b = Buffer.alloc(4)\n b.writeInt32LE(body.length, 0)\n const m = toSignedLittleBuffer(msgId, 8)\n buffer.write(Buffer.concat([m, s, b]))\n buffer.write(body)\n return msgId\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey()\n const s = toSignedLittleBuffer(this.salt,8)\n const i = toSignedLittleBuffer(this.id,8)\n data = Buffer.concat([Buffer.concat([s,i]), data])\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12)\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey().slice(88, 88 + 32), data, padding]))\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24)\n\n const { iv, key } = await this._calcKey(this.authKey.getKey(), msgKey, true)\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8)\n return Buffer.concat([keyId, msgKey, new IGE(key,iv).encryptIge(Buffer.concat([data, padding]))])\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body)\n }\n\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8))\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key')\n }\n\n const msgKey = body.slice(8, 24)\n const { iv, key } = await this._calcKey(this.authKey.getKey(), msgKey, false)\n body = new IGE(key,iv).decryptIge(body.slice(24))\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey().slice(96, 96 + 32), body]))\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one')\n }\n\n const reader = new BinaryReader(body)\n reader.readLong() // removeSalt\n const serverId = reader.readLong()\n if (serverId !== this.id) {\n // throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong()\n const remoteSequence = reader.readInt()\n reader.readInt() // msgLen for the inner object, padding ignored\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject()\n\n return new TLMessage(remoteMsgId, remoteSequence, obj)\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9)\n let newMsgId = (BigInt(Math.floor(now)).shiftLeft(BigInt(32))).or(BigInt(nanoseconds).shiftLeft(BigInt(2)))\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4))\n }\n this._lastMsgId = newMsgId\n return newMsgId\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId()\n const old = this.timeOffset\n const now = Math.floor(new Date().getTime() / 1000)\n const correct = correctMsgId.shiftRight(BigInt(32))\n this.timeOffset = correct - now\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0)\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n )\n }\n\n return this.timeOffset\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1\n this._sequence += 1\n return result\n } else {\n return this._sequence * 2\n }\n }\n}\n\nmodule.exports = MTProtoState\n","const Helpers = require(\"../Helpers\");\n\nconst {IGE:aes_ige} = require('@cryptography/aes');\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new aes_ige(key,iv);\n }\n\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n encryptIge(plainText) {\n const padding = plainText.length % 16\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)])\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n\n\n }\n\n}\n\nmodule.exports = IGENEW\n","const BigInt = require('big-integer')\nconst IGE = require('../crypto/IGE')\nconst AuthKey = require('../crypto/AuthKey')\nconst Factorizator = require('../crypto/Factorizator')\nconst RSA = require('../crypto/RSA')\nconst Helpers = require('../Helpers')\nconst { constructors, requests } = require('../tl')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { SecurityError } = require(\"../errors/Common\")\n\n/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\nasync function doAuthentication(sender, log) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16)\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true)\n\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce: nonce }))\n log.debug('Starting authKey generation step 1')\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`Step 1 answer was ${resPQ}`)\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server')\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true)\n log.debug('Finished authKey generation step 1')\n log.debug('Starting authKey generation step 2')\n // Step 2 sending: DH Exchange\n let { p, q } = Factorizator.factorize(pq)\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p)\n q = Helpers.getByteArray(q)\n\n bytes = Helpers.generateRandomBytes(32)\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true)\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p: p,\n q: q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce: newNonce,\n })\n\n // sha_digest + data + random_bytes\n let cipherText = null\n let targetFingerprint = null\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes())\n if (cipherText !== null && cipherText !== undefined) {\n targetFingerprint = fingerprint\n break\n }\n }\n if (cipherText === null || cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints')\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: p,\n q: q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n )\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk || serverDhParams instanceof constructors.ServerDHParamsFail)) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`)\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server')\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server')\n }\n\n if (serverDhParams instanceof constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32).slice(4, 20))\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true)\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server')\n }\n }\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`)\n }\n log.debug('Finished authKey generation step 2')\n log.debug('Starting authKey generation step 3')\n\n // Step 3 sending: Complete DH Exchange\n const { key, iv } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce)\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch')\n }\n const ige = new IGE(key,iv)\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer)\n const reader = new BinaryReader(plainTextAnswer)\n reader.read(20) // hash sum\n const serverDhInner = reader.tgReadObject()\n if (!(serverDhInner instanceof constructors.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`)\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer')\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 3 Invalid server nonce in encrypted answer')\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false)\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false)\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000)\n const b = Helpers.readBigIntFromBuffer(Helpers.generateRandomBytes(256), false, false)\n const gb = Helpers.modExp(BigInt(serverDhInner.g), b, dhPrime)\n const gab = Helpers.modExp(ga, b, dhPrime)\n\n // Prepare client DH Inner Data\n const clientDhInner = new constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes()\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner])\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed)\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n )\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail]\n if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {\n throw new Error(`Step 3.1 answer was ${dhGen}`)\n }\n const { name } = dhGen.constructor\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`)\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(`Step 3 invalid ${name} server nonce from server`)\n }\n const authKey = new AuthKey()\n await authKey.setKey(Helpers.getByteArray(gab))\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor)\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber)\n const dhHash = dhGen[`newNonceHash${nonceNumber}`]\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash')\n }\n\n if (!(dhGen instanceof constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`)\n }\n log.debug('Finished authKey generation step 3')\n\n return { authKey, timeOffset }\n}\n\n\nmodule.exports = doAuthentication\n","const BigInt = require('big-integer')\nconst { modExp } = require('../Helpers')\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(BigInt.zero)) {\n let temp = b\n b = a.remainder(b)\n a = temp\n }\n return a\n }\n\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n static factorize(pq) {\n if (pq.remainder(2).equals(BigInt.zero)) {\n return { p: BigInt(2), q: pq.divide(BigInt(2)) }\n }\n let y = BigInt.randBetween(BigInt(1),pq.minus(1))\n const c = BigInt.randBetween(BigInt(1),pq.minus(1))\n const m = BigInt.randBetween(BigInt(1),pq.minus(1))\n\n let g = BigInt.one\n let r = BigInt.one\n let q = BigInt.one\n let x = BigInt.zero\n let ys = BigInt.zero\n let k\n\n while (g.eq(BigInt.one)) {\n x = y\n for (let i = 0; BigInt(i).lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c).remainder(pq)\n }\n k = BigInt.zero\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n\n ys = y\n let condition = BigInt.min(m, r.minus(k))\n for (let i = 0; BigInt(i).lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c).remainder(pq)\n q = q.multiply(x.minus(y).abs()).remainder(pq)\n }\n g = Factorizator.gcd(q, pq)\n k = k.add(m)\n }\n\n r = r.multiply(2)\n }\n\n\n if (g.eq(pq)) {\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c).remainder(pq)\n g = Factorizator.gcd(x.minus(ys).abs(), pq)\n\n if (g.greater(1)) {\n break\n }\n }\n }\n const p = g\n q = pq.divide(g)\n return p < q ? { p: p, q: q } : { p: q, q: p }\n }\n}\n\nmodule.exports = Factorizator\n","const { readBufferFromBigInt } = require('../../Helpers')\nconst { Connection, PacketCodec } = require('./Connection')\nconst BigInt = require('big-integer')\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex')\n static obfuscateTag = Buffer.from('efefefef', 'hex')\n\n constructor(props) {\n super(props)\n this.tag = AbridgedPacketCodec.tag\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag\n }\n\n encodePacket(data) {\n let length = data.length >> 2\n if (length < 127) {\n const b = Buffer.alloc(1)\n b.writeUInt8(length, 0)\n length = b\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)])\n }\n return Buffer.concat([length, data])\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1)\n let length = readData[0]\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0)\n }\n\n return await reader.read(length << 2)\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n}\n","const { generateRandomBytes } = require('../../Helpers')\nconst { ObfuscatedConnection } = require('./Connection')\nconst { AbridgedPacketCodec } = require('./TCPAbridged')\nconst CTR = require('../../crypto/CTR')\n\nclass ObfuscatedIO {\n header = null\n\n constructor(connection) {\n this.connection = connection.socket\n const res = this.initHeader(connection.PacketCodecClass)\n this.header = res.random\n\n this._encrypt = res.encryptor\n this._decrypt = res.decryptor\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')]\n let random\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64)\n if (random[0] !== 0xef && !(random.slice(4, 8).equals(Buffer.alloc(4)))) {\n let ok = true\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false\n break\n }\n }\n if (ok) {\n break\n }\n }\n }\n random = random.toJSON().data\n\n const randomReversed = Buffer.from(random.slice(8, 56)).reverse()\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40))\n const encryptIv = Buffer.from(random.slice(40, 56))\n const decryptKey = Buffer.from(randomReversed.slice(0, 32))\n const decryptIv = Buffer.from(randomReversed.slice(32, 48))\n const encryptor = new CTR(encryptKey, encryptIv)\n const decryptor = new CTR(decryptKey, decryptIv)\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ])\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random).slice(56, 64)),Buffer.from(random.slice(64)) ,\n ])\n return { random, encryptor, decryptor }\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n)\n return this._decrypt.encrypt(data)\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data))\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO\n PacketCodecClass = AbridgedPacketCodec\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n}\n\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n\n uint8[i++] = int >>> 24;\n uint8[i++] = (int >> 16) & 0xFF;\n uint8[i++] = (int >> 8) & 0xFF;\n uint8[i++] = int & 0xFF;\n }\n\n return uint8.buffer;\n}\n\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === 'string') {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += '\\0x00';\n\n const buf = new Uint32Array(key.length / 4);\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#23ab23d2 flags:# id:InputDocument ttl_seconds:flags.0?int = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#f4e096c3 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#27d69997 flags:# big:flags.0?true peer:InputPeer volume_id:long local_id:int = InputFileLocation;\ninputStickerSetThumb#dbaeae9 stickerset:InputStickerSet volume_id:long local_id: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 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#69d3ab26 flags:# has_video:flags.0?true photo_id:long photo_small:FileLocation photo_big:FileLocation 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 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 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#1b7c9db3 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:ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int = ChatFull;\nchannelFull#f0e6672a 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: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 = 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#d20b9f3c flags:# has_video:flags.0?true photo_small:FileLocation photo_big:FileLocation dc_id:int = ChatPhoto;\nmessageEmpty#83e5de54 id:int = Message;\nmessage#58ae39c9 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 = Message;\nmessageService#286fa604 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 = 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;\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#77bfb61b type:string location:FileLocation w:int h:int size:int = PhotoSize;\nphotoCachedSize#e9a734fa type:string location:FileLocation w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#5aa86a51 type:string location:FileLocation 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 geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#e1746d0a text:string = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\nuserFull#edf17c12 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 = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#9a65ea1f chat_id:int user_id:int action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#12b9417b user_id:int phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#54826690 flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#e73547e1 flags:# query_id:long user_id:int peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#42f88f2c poll_id:long user_id:int options:Vector = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelParticipant#65d2b464 flags:# channel_id:int date:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant qts:int = Update;\nupdateChannelMessageForwards#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#ff2abe9f flags:# channel_id:int top_msg_id:flags.0?int user_id:int action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#2296d2c8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShortChatMessage#402d5dbb flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#11f1331c flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#13d6dd27 id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteEmpty#69df3769 = ExportedChatInvite;\nchatInviteExported#fc2e05bc link:string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#eeb46f27 flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumb:flags.4?PhotoSize thumb_dc_id:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#1c0facaf flags:# left:flags.0?true user_id:int kicked_by:int date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#c3c6796b user_id:int = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#f56ee2a8 count:int participants:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#d0d9b163 participant:ChannelParticipant users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#2e0709a5 hash:int gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#58fffcd0 pos:int user_id:int score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#c30aa358 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#3f56aea3 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#500911e1 flags:# date:int bot_id:int invoice:Invoice provider_id:int info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsAndroidPay#ca05d50e payment_token:DataJSON google_transaction_id:string = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#cac943f2 hash:long bot_id:int domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#5108d648 hash:int sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#badcc1a3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfileLocationToBeDeprecated#bc7fc6cd volume_id:long local_id:int = FileLocation;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\n// Some unused classes were removed below this line\nvideoSize#e831c556 flags:# type:string location:FileLocation w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nmessages.discussionMessage#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector = Bool;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#d4982db5 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#df7534c peer:InputPeer = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = channels.ChannelParticipants;\nchannels.getParticipant#546dd7a6 channel:InputChannel user_id:InputUser = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#72796912 channel:InputChannel user_id:InputUser banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#99f09745 msg_id:int = payments.PaymentForm;\npayments.getPaymentReceipt#a092a980 msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#770a8e74 flags:# save:flags.0?true msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#2b8879b3 flags:# msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 121\n`;","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const Logger = require('../extensions/Logger')\nconst { sleep } = require('../Helpers')\nconst errors = require('../errors')\nconst MemorySession = require('../sessions/Memory')\nconst Helpers = require('../Helpers')\nconst { BinaryWriter } = require('../extensions')\nconst utils = require('../Utils')\nconst Session = require('../sessions/Abstract')\nconst os = require('os')\nconst { LAYER } = require('../tl/AllTLObjects')\nconst { constructors, requests } = require('../tl')\nconst MTProtoSender = require('../network/MTProtoSender')\nconst { UpdateConnectionState } = require(\"../network\")\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')\nconst { authFlow, checkAuthorization } = require('./auth')\nconst { downloadFile } = require('./downloadFile')\nconst { uploadFile } = require('./uploadFile')\nconst { updateTwoFaSettings } = require('./2fa')\n\nconst DEFAULT_DC_ID = 2\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org'\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]'\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's']\n\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: null,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: null,\n systemVersion: null,\n appVersion: null,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n }\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (apiId === undefined || apiHash === undefined) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md')\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts }\n this.apiId = apiId\n this.apiHash = apiHash\n this._useIPV6 = args.useIPV6\n // this._entityCache = new Set()\n if (typeof args.baseLogger == 'string') {\n this._log = new Logger()\n } else {\n this._log = args.baseLogger\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented')\n } catch (e) {\n session = new MemorySession()\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance')\n }\n\n this.floodSleepLimit = args.floodSleepLimit\n this._eventBuilders = []\n\n this._phoneCodeHash = {}\n this.session = session\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId)\n this.apiHash = apiHash\n\n this._requestRetries = args.requestRetries\n this._connectionRetries = args.connectionRetries\n this._retryDelay = args.retryDelay || 0\n if (args.proxy) {\n this._log.warn('proxies are not supported')\n }\n this._proxy = args.proxy\n this._timeout = args.timeout\n this._autoReconnect = args.autoReconnect\n\n this._connection = args.connection\n // TODO add proxy support\n\n this._floodWaitedRequests = {}\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: null, // no proxies yet.\n }),\n })\n }\n\n this._args = args\n // These will be set later\n this._config = null\n this.phoneCodeHashes = []\n this._borrowedSenderPromises = {}\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\n\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession()\n\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n })\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log\n )\n\n await this._sender.connect(connection)\n\n this.session.setAuthKey(this._sender.authKey)\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ))\n\n this._updateLoop()\n }\n\n async _initSession() {\n await this.session.load()\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6 ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80)\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000)\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)\n })), 1500)\n }, 3, 100)\n } catch (err) {\n await this.disconnect()\n this.connect()\n\n return\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState())\n } catch (e) {\n\n }\n }\n }\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect()\n }\n\n await Promise.all(\n Object.values(this._borrowedSenderPromises).map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect()\n }\n })\n })\n )\n\n this._borrowedSenderPromises = {}\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect()\n this.session.delete()\n this._eventBuilders = []\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`)\n const DC = utils.getDC(newDc)\n this.session.setDC(newDc, DC.ipAddress, DC.port)\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(null)\n this.session.setAuthKey(null)\n await this.disconnect()\n return this.connect()\n }\n\n async _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId)\n }\n\n // endregion\n // export region\n\n _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId]\n }\n\n async _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId]\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId)\n this._borrowedSenderPromises[dcId] = senderPromise\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId]\n }\n });\n }\n return senderPromise\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId)\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\n logger: this._log,\n dcId: dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupBorrowedSender.bind(this),\n })\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ))\n if (this.session.dcId !== dcId) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`)\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId: dcId }))\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n },\n ))\n await sender.send(req)\n }\n sender.dcId = dcId\n return sender\n } catch (e) {\n await sender.disconnect()\n }\n }\n return null\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n async downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args)\n }\n\n async downloadMedia(messageOrMedia, args) {\n let date\n let media\n if (messageOrMedia instanceof constructors.Message) {\n date = messageOrMedia.date\n media = messageOrMedia.media\n } else {\n date = new Date().getTime()\n media = messageOrMedia\n }\n if (typeof media == 'string') {\n throw new Error('not implemented')\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args)\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args)\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args)\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args)\n }\n }\n\n async downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697]\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm'\n let photo\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return null\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n )\n }\n photo = entity.photo\n }\n\n let dcId\n let loc\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId\n const size = isBig ? photo.photoBig : photo.photoSmall\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n localId: size.localId,\n volumeId: size.volumeId,\n big: isBig,\n })\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return null\n }\n try {\n return this.downloadFile(loc, {\n dcId: dcId,\n })\n } catch (e) {\n // TODO this should never raise\n throw e;\n /*if (e.message === 'LOCATION_INVALID') {\n const ie = await this.getInputEntity(entity)\n if (ie instanceof constructors.InputPeerChannel) {\n const full = await this.invoke(new requests.channels.GetFullChannel({\n channel: ie,\n }))\n return this._downloadPhoto(full.fullChat.chatPhoto, { sizeType })\n } else {\n return null\n }\n } else {\n throw e\n }*/\n }\n }\n\n async downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumb || !stickerSet.thumb.location) {\n return undefined\n }\n\n const { location } = stickerSet.thumb\n\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash\n }),\n localId: location.localId,\n volumeId: location.volumeId,\n }),\n { dcId: stickerSet.thumbDcId }\n )\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return null\n }\n const indexOfSize = sizeTypes.indexOf(sizeType)\n let size\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i])\n if (size) {\n return size\n }\n }\n return null\n }\n\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes)\n } else {\n data = size.bytes\n }\n return data\n }\n\n async _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo\n }\n if (!(photo instanceof constructors.Photo)) {\n return\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType)\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size)\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n )\n }\n\n async _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document\n }\n if (!(doc instanceof constructors.Document)) {\n return\n }\n\n let size = null\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : null\n if (!size && doc.mimeType.startsWith('video/')) {\n return\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size)\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n )\n }\n\n _downloadContact(media, args) {\n throw new Error('not implemented')\n }\n\n _downloadWebDocument(media, args) {\n throw new Error('not implemented')\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests')\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime()\n let attempt = 0\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request)\n const result = await promise\n //this.session.processEntities(result)\n // this._entityCache.add(result)\n return result\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL' ||\n e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`)\n await sleep(2000)\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`)\n await sleep(e.seconds * 1000)\n } else {\n throw e\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError ||\n e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`)\n const shouldRaise = e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n if (shouldRaise && await checkAuthorization(this)) {\n throw e\n }\n await this._switchDC(e.newDc)\n } else {\n throw e\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`)\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0]\n } catch (e) {\n }\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect()\n }\n\n if (await checkAuthorization(this)) {\n return\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash\n }\n\n await authFlow(this, apiCredentials, authParams)\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams)\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback])\n }\n\n _handleUpdate(update) {\n //this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = []\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x)\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities)\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, null)\n } else {\n this._processUpdate(update, null)\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || []\n const args = {\n update: update,\n others: others,\n }\n this._dispatchUpdate(args)\n }\n\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /*CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n /*CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: null,\n others: null,\n channelId: null,\n ptsDate: null,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update)\n if (event) {\n await callback(event)\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true\n }\n }\n return false\n }\n}\n\nasync function timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms).then(() => Promise.reject(new Error('TIMEOUT'))),\n ])\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n return await cb()\n } catch (err) {\n if (i === times - 1) {\n throw err\n }\n\n await Helpers.sleep(pause)\n }\n }\n}\n\nmodule.exports = TelegramClient\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\n","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","const BigInt = require('big-integer')\nconst { readBigIntFromBuffer, readBufferFromBigInt, getByteArray, sha1, generateRandomBytes, modExp } = require('../Helpers')\n\nconst PUBLIC_KEYS = [{\n 'fingerprint': [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n 'n': BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n 'e': 65537\n}, {\n 'fingerprint': [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n 'n': BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n 'e': 65537\n}, {\n 'fingerprint': [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n 'n': BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n 'e': 65537\n}, {\n 'fingerprint': [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n 'n': BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n 'e': 65537\n}]\n\nconst _serverKeys = {}\n\nPUBLIC_KEYS.forEach(({ fingerprint, ...keyInfo }) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = keyInfo\n})\n\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint]\n if (!key) {\n return undefined\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length)\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand])\n\n // rsa module rsa.encrypt adds 11 bits for padding which we don't want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n const payload = readBigIntFromBuffer(toEncrypt, false)\n const encrypted = modExp(payload, BigInt(key.e), key.n)\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false)\n}\n\nmodule.exports = {\n encrypt,\n}\n","class RequestState {\n constructor(request, after = null) {\n this.containerId = null\n this.msgId = null\n this.request = request\n this.data = request.getBytes()\n this.after = after\n this.result = null\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve\n this.reject = reject\n })\n }\n}\n\nmodule.exports = RequestState\n","const { Connection } = require('./Connection')\nconst { ConnectionTCPFull } = require('./TCPFull')\nconst { ConnectionTCPAbridged } = require('./TCPAbridged')\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated')\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n}\n","const crypto = require('./crypto')\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error('Key and iv need to be a buffer')\n }\n\n this.cipher = crypto.createCipheriv('AES-256-CTR', key, iv)\n }\n\n encrypt(data) {\n return Buffer.from(this.cipher.update(data))\n }\n}\n\nmodule.exports = CTR\n","import { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer, expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number,\n apiHash: string,\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n while (1) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n while (1) {\n if (isScanningComplete){\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n}> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","import { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\n\nexport interface progressCallback {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst REQUEST_TIMEOUT = 15000;\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let { partSizeKb, fileSize, workers = 1, end } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - offset % ONE_MB;\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n await foreman.releaseWorker();\n break;\n }\n\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\n ]);\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n\nclass Foreman {\n private deferred: Deferred | undefined;\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && (this.activeWorkers <= this.maxWorkers)) {\n this.deferred.resolve();\n }\n }\n}\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\n}\n","import { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\n\ninterface OnProgress {\n // Float between 0 and 1.\n (progress: number): void;\n\n isCanceled?: boolean;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst UPLOAD_TIMEOUT = 15 * 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n let sendingParts = [];\n let end = i + workers;\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n sendingParts.push((async () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\n );\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partCount);\n onProgress(progress);\n }\n })());\n\n }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: '', // This is not a \"flag\", so not sure if we can make it optional.\n });\n}\n\nfunction generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), false);\n}\n\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","import TelegramClient from './TelegramClient';\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password: password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n while (1) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2'\n","const NewMessage = require('./NewMessage')\nconst Raw = require('./Raw')\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = { NewMessage, StopPropagation, Raw }\n","const { EventBuilder } = require('./common')\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: null,\n func: null,\n }) {\n super()\n if (!args.types) {\n this.types = true\n } else {\n this.types = args.types\n }\n }\n\n build(update, others = null) {\n return update\n }\n}\n\nmodule.exports = Raw\n","class EventBuilder {\n constructor(args = {\n chats: null, blacklistChats: null, func: null,\n },\n ) {\n this.chats = args.chats\n this.blacklistChats = Boolean(args.blacklistChats)\n this.resolved = false\n this.func = args.func\n }\n\n build(update, others = null) {\n\n }\n}\n\nclass EventCommon {\n\n}\n\n\nmodule.exports = { EventBuilder, EventCommon }\n","const Memory = require('./Memory')\nconst StringSession = require('./StringSession')\nconst CacheApiSession = require('./CacheApiSession')\nconst LocalStorageSession = require('./LocalStorageSession')\nconst IdbSession = require('./IdbSession')\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n}\n","const MemorySession = require('./Memory')\nconst AuthKey = require('../crypto/AuthKey')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst CURRENT_VERSION = '1'\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = null) {\n super()\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string')\n }\n session = session.slice(1)\n const r = StringSession.decode(session)\n const reader = new BinaryReader(r)\n this._dcId = reader.read(1)\n .readUInt8(0)\n const serverAddressLen = reader.read(2)\n .readInt16BE(0)\n this._serverAddress = String(reader.read(serverAddressLen))\n this._port = reader.read(2)\n .readInt16BE(0)\n this._key = reader.read(-1)\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64')\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64')\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey()\n await this._authKey.setKey(this._key)\n }\n }\n\n save() {\n if (!this.authKey) {\n return ''\n }\n const dcBuffer = Buffer.from([this.dcId])\n const addressBuffer = Buffer.from(this.serverAddress)\n const addressLengthBuffer = Buffer.alloc(2)\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0)\n const portBuffer = Buffer.alloc(2)\n portBuffer.writeInt16BE(this.port, 0)\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]))\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined\n }\n\n return this.authKey\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined\n }\n\n this.authKey = authKey\n }\n}\n\nmodule.exports = StringSession\n","const StorageSession = require('./StorageSession')\n\nconst CACHE_NAME = 'GramJs'\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey)\n const cache = await self.caches.open(CACHE_NAME)\n return cache.delete(request)\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey)\n const cache = await self.caches.open(CACHE_NAME)\n const cached = await cache.match(request)\n return cached ? cached.text() : null\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey)\n const response = new Response(data)\n const cache = await self.caches.open(CACHE_NAME)\n return cache.put(request, response)\n }\n}\n\nmodule.exports = CacheApiSession\n","const StorageSession = require('./StorageSession')\n\nclass LocalStorageSession extends StorageSession {\n async _delete() {\n return localStorage.removeItem(this._storageKey)\n }\n\n async _fetchFromCache(key) {\n return localStorage.getItem(this._storageKey)\n }\n\n async _saveToCache(key, data) {\n return localStorage.setItem(this._storageKey, data)\n }\n}\n\nmodule.exports = LocalStorageSession\n","const StorageSession = require('./StorageSession')\nconst idb = require('idb-keyval')\n\nconst CACHE_NAME = 'GramJs'\n\nclass IdbSession extends StorageSession {\n async _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`)\n }\n\n async _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`)\n }\n\n async _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data)\n }\n}\n\nmodule.exports = IdbSession\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumb) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: result.hash,\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n hash: result.hash,\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function loadNotificationsSettings() {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n isShowPreviews,\n}: {\n isSilent: boolean;\n isShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: isShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : undefined,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({ langPack, langCode }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: IInputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nfunction updateLocalDb(result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import { ApiOnProgress, ApiUpdate, OnApiUpdate } from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionId = '') {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(sessionId, handleUpdate);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/process/browser.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","sessionId","_onUpdate","DEBUG","log","session","IS_TEST","LocalStorageSession","IdbSession","process","useWSS","additionalDcsDisabled","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","newSessionId","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","result","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","length","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","nonStrippedSizes","sizes","PhotoSize","PhotoCachedSize","smallSize","find","largeSize","ChatPhoto","photoSmall","location","photoBig","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restricted","restrictionReason","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","toString","restrictionReasons","targetReason","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","UserProfilePhoto","photoId","volumeId","localId","buildChatMember","member","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatInviteLink","exportedInvite","ChatInviteExported","link","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateChatUserTyping","UpdateChannelUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","readBufferFromBigInt","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","api","fromReader","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","byte","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","firstMessageId","Messages","offsetId","offsetIdOffset","offsetIdIndex","findIndex","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","discussionChatId","topMessageId","ChannelMessages","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","addOffset","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","subarray","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","reduce","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","flags","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","patched","JPEG_HEADER","RegExp","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","cdn","ipAddress","port","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","UpdateUserTyping","typingStatus","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","showPreviews","peerType","isShowPreviews","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","RPCError","rpcErrorRe","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","setDC","serverAddress","_authKey","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","Logger","BinaryWriter","PromisedWebSockets","MessagePacker","AsyncQueue","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","before","tlMessage","MTProtoPlainSender","doAuthentication","MTProtoSender","Connection","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","_storageKey","_authKeys","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","sessionData","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","fromLine","line","argsMatch","findAll","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","regex","matches","exec","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","_stream","getValue","RPCResult","RpcError","reqMsgId","body","innerCode","LAYER","mutex","Mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","send","onmessage","release","acquire","logger","_state","_queue","_pendingStates","_ready","setReady","append","promise","catch","finally","extend","states","batch","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","after","writeDataAsMessage","containerId","rejectAll","requestState","canGet","resolveGet","canPush","resolvePush","returned","MtProtoPlainSender","MTProtoState","Helpers","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","DEFAULT_OPTIONS","_connection","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","plain","setKey","time_offset","timeOffset","ack","msgIds","encryptMessageData","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","innerMessage","pong","badSalt","badMsgId","newServerSalt","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","nanoseconds","newMsgId","correctMsgId","bad","old","aes_ige","ige","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","ys","condition","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","webpackPolyfill","deprecate","paths","children","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","deviceModel","systemVersion","appVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","_lastRequest","GetState","DC","_cleanupBorrowedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","race","sequentialUpdates","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","endianness","hostname","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","navigator","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","partSizeKb","partSize","partsCount","_borrowExportedSender","foreman","Foreman","promises","hasEnded","requestWorker","releaseWorker","GetFile","precise","totalLength","maxWorkers","activeWorkers","deferred","_resolve","createDeferred","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","EventCommon","Memory","StringSession","CacheApiSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","loadNotificationsSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,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6rD,GAE7B15E,EAAKwU,KAAKklE,GAGZ,MAAMvkF,QDbP,SAA0CuiG,KAAc13F,GAE7D,OAAOs/D,EAAQo4B,MAAW13F,GCWG23F,CAAQzlG,KAAS8N,IAClC,YAAE3I,GAAqC,iBAAblC,GAAyB,gBAAiBA,GAAYA,GAAa,GAE/F04B,GACFupE,GAAa,CACXtiG,KAAM,iBACN+4B,YACA14B,YACCkC,GAEL,MAAOqI,GACHvD,KAEFpG,QAAQ2J,MAAMA,GAGZmuB,GACFupE,GAAa,CACXtiG,KAAM,iBACN+4B,YACAnuB,MAAO,CAAEvG,QAASuG,EAAMvG,WAK1B00B,GACFwpE,GAAc5gG,OAAOo3B,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAM6rD,EAAW2d,GAAc7kG,IAAI0D,EAAK23B,WACpC6rD,IACgBA,EDzCPr/C,YAAa,GC4C1B","file":"e1066b23c5448d0199e4.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 109);\n","const Api = require('./tl/api')\nconst TelegramClient = require('./client/TelegramClient')\nconst connection = require('./network')\nconst tl = require('./tl')\nconst version = require('./Version')\nconst events = require('./events')\nconst utils = require('./Utils')\nconst errors = require('./errors')\nconst sessions = require('./sessions')\nconst extensions = require('./extensions')\nconst helpers = require('./Helpers')\n\nmodule.exports = {\n Api, TelegramClient, sessions, connection, extensions,\n tl, version, events, utils, errors, helpers,\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : 'image/jpeg';\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = 'image/jpeg';\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport { ApiMediaFormat, ApiOnProgress, OnApiUpdate } from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(sessionId: string, _onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n const session = IS_TEST\n ? new sessions.LocalStorageSession(sessionId)\n : new sessions.IdbSession(sessionId);\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n }\n\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n });\n\n const newSessionId = await session.save();\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED as ', newSessionId);\n }\n\n onAuthReady(newSessionId);\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ${request.className} ERROR: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId } = photo;\n const nonStrippedSizes = photo.sizes\n .filter((s: any): s is (GramJs.PhotoSize | GramJs.PhotoCachedSize) => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoCachedSize;\n });\n\n if (!nonStrippedSizes.length) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const smallSize = nonStrippedSizes.find((s) => s.type === 'a');\n const largeSize = nonStrippedSizes.find((s) => s.type === 'c') || nonStrippedSizes.find((s) => s.type === 'b');\n\n if (!smallSize || !largeSize) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n return new GramJs.ChatPhoto({\n dcId,\n photoSmall: smallSize && smallSize.location,\n photoBig: largeSize && largeSize.location,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatMember,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiRestrictionReason,\n ApiChatFolder,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isPeerChat,\n isPeerUser,\n isInputPeerUser,\n isInputPeerChat,\n isInputPeerChannel,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n if (peerEntity instanceof GramJs.User) {\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: peerEntity.migratedTo.accessHash.toString(),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: any) {\n if (photo instanceof GramJs.UserProfilePhoto) {\n return photo.photoId.toString();\n } else if (photo instanceof GramJs.ChatPhoto) {\n const { dcId, photoSmall: { volumeId, localId } } = photo;\n return `${dcId}-${volumeId}-${localId}`;\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember {\n return {\n userId: member.userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n): ApiChatMember[] | undefined {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember);\n }\n\n return undefined;\n}\n\nexport function buildChatInviteLink(exportedInvite: GramJs.TypeExportedChatInvite) {\n return exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n}\n\nexport function buildChatTypingStatus(update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'recording a video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'uploading a video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'recording a voice message';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'uploading a voice message';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'uploading a photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'uploading a file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'playing a game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'recording a round video';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'uploading a round video';\n }\n\n return {\n action,\n ...(update instanceof GramJs.UpdateChatUserTyping && { userId: update.userId }),\n ...(update instanceof GramJs.UpdateChannelUserTyping && { userId: update.userId }),\n timestamp: Date.now(),\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\n","const {\n parseTl,\n serializeBytes,\n serializeDate\n} = require('./generationHelpers')\nconst { readBufferFromBigInt,toSignedLittleBuffer } = require('../Helpers')\n\nconst tlContent = require('./apiTl.js')\nconst schemeContent = require('./schemaTl.js')\n\n/*CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined\n\nconst CACHE_KEY = 'GramJs:apiCache'\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache()\n\n if (fromCache) {\n definitions = fromCache\n } else {\n definitions = loadFromTlSchemas()\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions))\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests)\n )\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY)\n return jsonCache && JSON.parse(jsonCache)\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent)\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent)\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema)\n const requests = [].concat(functionParamsApi, functionParamsSchema)\n\n return { constructors, requests }\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 }\n\n Object.keys(obj2).forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key]\n } else {\n Object.assign(result[key], obj2[key])\n }\n })\n\n return result\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109)\n const constructors = []\n const functions = []\n for (const d of f) {\n d.isFunction ? functions.push(d) : constructors.push(d)\n }\n return [constructors, functions]\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int':\n const i = Buffer.alloc(4)\n i.writeInt32LE(x, 0)\n return i\n case 'long':\n return toSignedLittleBuffer(x, 8)\n case 'int128':\n return toSignedLittleBuffer(x, 16)\n case 'int256':\n return toSignedLittleBuffer(x, 32)\n case 'double':\n const d = Buffer.alloc(8)\n d.writeDoubleLE(x, 0)\n return d\n case 'string':\n return serializeBytes(x)\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex')\n case 'true':\n return Buffer.alloc(0)\n case 'bytes':\n return serializeBytes(x)\n case 'date':\n return serializeDate(x)\n default:\n return x.getBytes()\n }\n}\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt()\n }\n const temp = []\n const len = reader.readInt()\n arg.isVector = false\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg))\n }\n arg.isVector = true\n return temp\n } else if (arg.flagIndicator) {\n return reader.readInt()\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt()\n case 'long':\n return reader.readLong()\n case 'int128':\n return reader.readLargeInt(128)\n case 'int256':\n return reader.readLargeInt(256)\n case 'double':\n return reader.readDouble()\n case 'string':\n return reader.tgReadString()\n case 'Bool':\n return reader.tgReadBool()\n case 'true':\n return true\n case 'bytes':\n return reader.tgReadBytes()\n case 'date':\n return reader.tgReadDate()\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject()\n } else {\n return api.constructors[arg.type].fromReader(reader)\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {}\n for (const classParams of params) {\n const { name, constructorId, subclassOfId, argsConfig, namespace, result } = classParams\n const fullName = [namespace, name].join('.').replace(/^\\./, '')\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId\n static SUBCLASS_OF_ID = subclassOfId\n static className = fullName\n static classType = classesType\n\n CONSTRUCTOR_ID = constructorId\n SUBCLASS_OF_ID = subclassOfId\n className = fullName\n classType = classesType\n\n constructor(args) {\n args = args || {}\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName]\n })\n }\n\n static fromReader(reader) {\n\n const args = {}\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName]\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args['flags'] & 1 << arg.flagIndex)\n continue\n }\n if (args['flags'] & 1 << arg.flagIndex) {\n args[argName] = getArgFromReader(reader, arg)\n } else {\n args[argName] = null\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags'\n }\n args[argName] = getArgFromReader(reader, arg)\n }\n }\n }\n return new VirtualClass(args)\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID\n const c = Buffer.alloc(4)\n c.writeUInt32LE(idForBytes, 0)\n const buffers = [c]\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg]===false&&argsConfig[arg].type===\"true\") || this[arg]===null || this[arg]===undefined){\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'))\n }\n const l = Buffer.alloc(4)\n l.writeInt32LE(this[arg].length, 0)\n buffers.push(l, Buffer.concat(this[arg].map(x => argToBytes(x, argsConfig[arg].type))))\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4))\n } else {\n let flagCalculate = 0\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f]===false&&argsConfig[f].type===\"true\") || this[f]===undefined || this[f]===null) {\n flagCalculate |= 0\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex\n }\n }\n }\n const f = Buffer.alloc(4)\n f.writeUInt32LE(flagCalculate, 0)\n buffers.push(f)\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type))\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1))\n boxed = boxed === boxed.toUpperCase()\n if (!boxed) {\n buffers.shift()\n }\n }\n }\n }\n\n }\n return Buffer.concat(buffers)\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance')\n }\n\n const m = result.match(/Vector<(int|long)>/)\n if (m) {\n reader.readInt()\n let temp = []\n let len = reader.readInt()\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt())\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong())\n }\n }\n return temp\n } else {\n return reader.tgReadObject()\n }\n }\n\n /*CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n }*/\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {}\n }\n classes[namespace][name] = VirtualClass\n\n } else {\n classes[name] = VirtualClass\n }\n }\n\n return classes\n}\n\nmodule.exports = buildApiFromTlSchema()\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildChatInviteLink,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n lastMessage,\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n inviteLink: buildChatInviteLink(exportedInvite),\n canViewMembers: true,\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: number; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n userId,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as number,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter = 'kicked' | 'admin' | 'recent';\n\nexport async function fetchMembers(\n chatId: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n","const crypto = require('./crypto/crypto')\nconst BigInt = require('big-integer')\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer)\n const bytesNumber = randBuffer.length\n if (little) {\n randBuffer = randBuffer.reverse()\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16)\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)))\n }\n return bigInt\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big)\n const byteArray = []\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i).and(255)\n }\n return Buffer.from(byteArray)\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt)\n const bitLength = bigInt.bitLength()\n\n const bytes = Math.ceil(bitLength / 8)\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert')\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned')\n }\n let below = false\n if (bigInt.lesser(BigInt(0))) {\n below = true\n bigInt = bigInt.abs()\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0')\n let l = Buffer.from(hex, 'hex')\n if (little) {\n l = l.reverse()\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false\n if (l[0] !== 0) {\n l[0] -= 1\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true\n continue\n }\n if (reminder) {\n l[i] -= 1\n reminder = false\n }\n l[i] = 255 - l[i]\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1]\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i]\n }\n }\n }\n return l\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed)\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m)\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count))\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n/*CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16)\n newNonce = toSignedLittleBuffer(newNonce, 32)\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce]))\n ])\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)])\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)])\n return {\n key: keyBuffer,\n iv: ivBuffer\n }\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4)\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1')\n shaSum.update(data)\n return shaSum.digest()\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256')\n shaSum.update(data)\n return shaSum.digest()\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n)\n let result = BigInt.one\n let x = a\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2))\n b = b.divide(BigInt(2))\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x)\n result = result.remainder(n)\n }\n x = x.multiply(x)\n x = x.remainder(n)\n }\n return result\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length\n const byteLength = Math.floor((bits + 8 - 1) / 8)\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed)\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min)\n max = Math.floor(max)\n return Math.floor(Math.random() * (max - min + 1)) + min\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c\n const crcTable = []\n for (let n = 0; n < 256; n++) {\n c = n\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1))\n }\n crcTable[n] = c\n }\n return crcTable\n}\n\nlet crcTable = null\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable()\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf)\n }\n let crc = -1\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index]\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8)\n }\n return (crc ^ (-1)) >>> 0\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n //calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n //isArrayLike,\n toSignedLittleBuffer,\n convertToLittle\n\n}\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\n ]);\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %product%`;\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_IMAGE_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n // Not sure if there is an easier way to do this\n let firstMessageId: number | undefined;\n if (result.messages.length) {\n if (result instanceof GramJs.messages.Messages) {\n firstMessageId = result.messages[result.messages.length - 1].id;\n } else if (pagination.offsetId && result.offsetIdOffset) {\n const offsetIdIndex = result.messages.findIndex((m) => m.id === pagination.offsetId);\n const lastIndex = result.messages.length - offsetIdIndex;\n if (lastIndex + result.offsetIdOffset >= result.count) {\n firstMessageId = result.messages[result.messages.length - 1].id;\n }\n }\n }\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n firstMessageId,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n}) {\n const isScheduled = message.date * 1000 > Date.now();\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate(chat);\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n });\n });\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n hash: calculateResultHash(messages.map((message) => message.id)),\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","import { ApiDocument } from './messages';\n\nexport * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\n\nexport interface ApiOnProgress {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface ApiAttachment {\n blobUrl: string;\n filename: string;\n mimeType: string;\n size: number;\n quick?: {\n width: number;\n height: number;\n duration?: number;\n };\n voice?: {\n duration: number;\n waveform: number[];\n };\n previewBlobUrl?: string;\n}\n\nexport interface ApiWallpaper {\n slug: string;\n document: ApiDocument;\n}\n\nexport interface ApiSession {\n hash: string;\n isCurrent: boolean;\n isOfficialApp: boolean;\n isPasswordPending: boolean;\n deviceModel: string;\n platform: string;\n systemVersion: string;\n appName: string;\n appVersion: string;\n dateCreated: number;\n dateActive: number;\n ip: string;\n country: string;\n region: string;\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo, notifySettings: { silent, muteUntil },\n } = mtpUserFull;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isMuted,\n ...(botInfo && { botDescription: botInfo.description }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","var bigInt = (function (undefined) {\r\n \"use strict\";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\n\r\n var supportsNativeBigInt = typeof BigInt === \"function\";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === \"undefined\") return Integer[0];\r\n if (typeof radix !== \"undefined\") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === \"number\") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === \"number\") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error(\"Cannot divide by zero\");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === \"number\") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === \"number\") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === \"number\") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don't know if it's prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === \"number\" ? v | LOBMASK_I :\r\n typeof v === \"bigint\" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === \"-\") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === \"1\" && absBase === 1) continue;\r\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === \"-\";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === \"<\") {\r\n var start = i;\r\n do { i++; } while (text[i] !== \">\" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + \" is not a valid character\");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return \"<\" + digit + \">\";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join('');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? \"-\" : \"\";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error(\"Invalid integer: \" + v);\r\n }\r\n var sign = v[0] === \"-\";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === \"+\") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(\".\");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\r\n text += (new Array(exp + 1)).join(\"0\");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? \"-\" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === \"number\") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === \"string\") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === \"bigint\") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid Phone Number',\n PHONE_CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady(sessionId: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateReady'),\n sessionId,\n });\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","export function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","const api = require('./api')\nconst { serializeBytes, serializeDate } = require('./generationHelpers')\nconst patched = null\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n patched,\n serializeBytes,\n serializeDate\n}\n","const { constructors } = require('./tl')\n\nconst USERNAME_RE = new RegExp('@|(?:https?:\\\\/\\\\/)?(?:www\\\\.)?' +\n '(?:telegram\\\\.(?:me|dog)|t\\\\.me)\\\\/(@|joinchat\\\\/)?')\n\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex')\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex')\n\nconst TG_JOIN_RE = new RegExp('tg:\\\\/\\\\/(join)\\\\?invite=')\n\nconst VALID_USERNAME_RE = new RegExp('^([a-z]((?!__)[\\\\w\\\\d]){3,30}[a-z\\\\d]|gif|vid|' +\n 'pic|bing|wiki|imdb|bold|vote|like|coub)$')\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`)\n}\n\n/**\n Gets the input peer for the given \"entity\" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn't a supported type\n or if ``check_hash is True`` but the entity's ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``check_hash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they're doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\n if (allowSelf && 'inputEntity' in entity) {\n return entity.inputEntity\n } else if ('entity' in entity) {\n return getInputPeer(entity.entity)\n } else {\n _raiseCastFail(entity, 'InputPeer')\n }\n }\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf()\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n })\n } else {\n throw new Error('User without accessHash or min info cannot be input')\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty ||\n entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id })\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash\n })\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input')\n }\n }\n if (entity instanceof constructors.ChannelForbidden) {\n // \"channelForbidden are never min\", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash\n })\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty()\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user)\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id })\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId)\n }\n\n _raiseCastFail(entity, 'InputPeer')\n}\n\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n/*CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n/*CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n/*CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return new constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n/*CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped\n }\n const header = Buffer.from(JPEG_HEADER)\n header[164] = stripped[1]\n header[166] = stripped[2]\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER])\n}\n\n/*CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, 'InputFileLocation')\n }\n if (location instanceof constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: '', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128\n }\n if (fileSize <= 786432000) { // 750MB\n return 256\n }\n if (fileSize <= 1572864000) { // 1500MB\n return 512\n }\n\n throw new Error('File size too large')\n}\n\n/*CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/*CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/*CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n/*CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === null || message === undefined) {\n return null\n }\n if (typeof message == 'number') {\n return message\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`)\n}\n\n\n/**\n * Parses the given phone, or returns `None` if it's invalid.\n * @param phone\n */\nfunction parsePhone(phone) {\n return phone.toString().replace(/[+()\\s-]/gm, '')\n}\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n/*CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`\n } else if (entity.firstName) {\n return entity.firstName\n } else if (entity.lastName) {\n return entity.lastName\n } else {\n return ''\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title\n }\n return ''\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n/*CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\nfunction getDC(dcId, cdn = false) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443\n }\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443\n }\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443\n }\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443\n }\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.web.telegram.org',\n port: 443\n }\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`)\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n }*/\n}\n\nmodule.exports = {\n getMessageId,\n //_getEntityPair,\n //getInputMessage,\n //getInputDialog,\n //getInputUser,\n //getInputChannel,\n getInputPeer,\n //parsePhone,\n //parseUsername,\n //getPeer,\n //getPeerId,\n getDisplayName,\n //resolveId,\n //isListLike,\n getAppropriatedPartSize,\n //getInputLocation,\n strippedPhotoToJpg,\n getDC\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumb,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumb),\n count,\n hash,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.')\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`)\n if (typeof alert !== 'undefined') {\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`)\n }\n this.invalidConstructorId = invalidConstructorId\n this.remaining = remaining\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\n */\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`)\n this.checksum = checksum\n this.validChecksum = validChecksum\n }\n}\n\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means \"forgotten/broken authorization key\", while\n */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code = null\n if (payload.length === 4) {\n code = -payload.readInt32LE(0)\n super(`Invalid response buffer (HTTP code ${code})`)\n } else {\n super(`Invalid response buffer (too short ${payload})`)\n }\n this.code = code\n this.payload = payload\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.']\n }\n super(...args)\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.')\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to ' +\n 'synchronize it using msg_id notifications and re-send the original message ' +\n 'with the “correct” msg_id or wrap it in a container with a new msg_id if the ' +\n 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be ' +\n 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id ' +\n 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message ' + '(this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a ' +\n 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower ' +\n 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with ' +\n 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with ' +\n 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n }\n\n constructor(request,code) {\n let errorMessage = BadMessageError.ErrorMessages[code] ||\n `Unknown error code (this should not happen): ${code}.`\n errorMessage+= ` Caused by ${request.className}`\n super(errorMessage)\n this.message = errorMessage\n this.code = code\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n","const { TypeNotFoundError } = require('../errors/Common')\nconst { coreObjects } = require('../tl/core')\nconst { tlobjects } = require('../tl/AllTLObjects')\nconst { readBigIntFromBuffer } = require('../Helpers')\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data\n this._last = null\n this.offset = 0\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0]\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res\n if (signed) {\n res = this.stream.readInt32LE(this.offset)\n } else {\n res = this.stream.readUInt32LE(this.offset)\n }\n this.offset += 4\n return res\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed)\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4).readFloatLE(0)\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been 0) {\n padding = 4 - padding\n this.read(padding)\n }\n\n return data\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes().toString('utf-8')\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false)\n if (value === 0x997275b5) {\n // boolTrue\n return true\n } else if (value === 0xbc799737) {\n // boolFalse\n return false\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`)\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt()\n return new Date(value * 1000)\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false)\n let clazz = tlobjects[constructorId]\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId\n if (value === 0x997275b5) {\n // boolTrue\n return true\n } else if (value === 0xbc799737) {\n // boolFalse\n return false\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = []\n const length = this.readInt()\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject())\n }\n return temp\n }\n\n clazz = coreObjects[constructorId]\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4) // Go back\n const pos = this.tellPosition()\n const error = new TypeNotFoundError(constructorId, this.read())\n this.setPosition(pos)\n throw error\n }\n }\n return clazz.fromReader(this)\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected')\n }\n const count = this.readInt()\n const temp = []\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject())\n }\n return temp\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = null\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[randomId.toString()];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now();\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: update.channelId,\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n const { silent, muteUntil } = update.notifySettings;\n\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n isMuted: silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000),\n },\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000)),\n isShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require(\"./RPCBaseErrors\")\nconst { rpcErrorRe } = require('./RPCErrorList')\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex)\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1]) : null\n return new Cls({ request: request, capture: capture })\n }\n }\n\n return new RPCError(rpcError.errorMessage, request)\n}\n\nmodule.exports = {\n RPCMessageToError,\n ...require('./Common'),\n ...require('./RPCBaseErrors'),\n ...require('./RPCErrorList'),\n}\n","type Scheduler = typeof requestAnimationFrame | typeof onTickEnd | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n requestAnimationFrame(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafCallbacks.unshift(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n return fastRaf(callback, true);\n}\n","const BigInt = require('big-integer')\nconst Factorizator = require('./crypto/Factorizator')\nconst { constructors } = require('./tl')\nconst { readBigIntFromBuffer, readBufferFromBigInt, sha256, bigIntMod, modExp,\n generateRandomBytes } = require('./Helpers')\nconst crypto = require('./crypto/crypto')\nconst SIZE_FOR_HASH = 256\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodP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0x6B, 0xC4, 0x65, 0xB0, 0xD6, 0xFF, 0x9C, 0xA3, 0x92, 0x8F, 0xEF, 0x5B, 0x9A, 0xE4,\n 0xE4, 0x18, 0xFC, 0x15, 0xE8, 0x3E, 0xBE, 0xA0, 0xF8, 0x7F, 0xA9, 0xFF, 0x5E, 0xED, 0x70, 0x05,\n 0x0D, 0xED, 0x28, 0x49, 0xF4, 0x7B, 0xF9, 0x59, 0xD9, 0x56, 0x85, 0x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 0x6F, 0x4F, 0xAD, 0xF0, 0x34, 0xB1, 0x04, 0x03, 0x11, 0x9C, 0xD8, 0xE3, 0xB9, 0x2F, 0xCC, 0x5B,\n ])\n if (goodPrime.equals(primeBytes)) {\n if ([ 3, 4, 5, 7 ].includes(g)) {\n return // It's good\n }\n }\n throw new Error(\"Changing passwords unsupported\")\n //checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number).greater(BigInt(0))))\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([ Buffer.alloc(SIZE_FOR_HASH - number.length), number ])\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false)\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp)\n\n const minDiffBitsCount = 2048 - 64\n const maxModExpSize = 256\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount ||\n modexp.bitLength() < minDiffBitsCount ||\n Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize)\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length)\n\n for (let i = 0; i < length; i++) {\n a[i] = a[i] ^ b[i]\n }\n\n return a\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512')\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([ algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1 ]))\n const hash2 = await sha256(Buffer.concat([ algo.salt2, hash1, algo.salt2 ]))\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000)\n return sha256(Buffer.concat([ algo.salt2, hash3, algo.salt2 ]))\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g)\n } catch (e) {\n throw new Error('bad p/g in password')\n }\n\n const value = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false))\n return bigNumForHash(value)\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`)\n }\n\n const pwHash = await computeHash(algo, password)\n const p = readBigIntFromBuffer(algo.p, false)\n const g = algo.g\n const B = readBigIntFromBuffer(request.srp_B, false)\n try {\n checkPrimeAndGood(algo.p, g)\n } catch (e) {\n throw new Error('bad /g in password')\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check')\n }\n const x = readBigIntFromBuffer(pwHash, false)\n const pForHash = numBytesForHash(algo.p)\n const gForHash = bigNumForHash(g)\n const bForHash = numBytesForHash(request.srp_B)\n const gX = modExp(BigInt(g), x, p)\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([ pForHash, gForHash ])), false)\n const kgX = bigIntMod(k.multiply(gX),p)\n const generateAndCheckRandom =async () => {\n const randomSize = 256\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize)\n const a = readBigIntFromBuffer(random, false)\n const A = modExp(BigInt(g), a, p)\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A)\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([ aForHash, bForHash ])), false)\n if (u.greater(BigInt(0))) {\n return [ a, aForHash, u ]\n }\n }\n }\n }\n const [ a, aForHash, u ] =await generateAndCheckRandom()\n const gB = bigIntMod(B.subtract(kgX),p)\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error('bad gB')\n }\n\n const ux = u.multiply(x)\n const aUx = a.add(ux)\n const S = modExp(gB, aUx, p)\n const [K, pSha ,gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2)\n ])\n const M1 = await sha256(Buffer.concat([\n xor(pSha,gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]))\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1: M1,\n\n })\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n}\n\n","const utils = require('../Utils')\nconst types = require('../tl').constructors\nconst Session = require('./Abstract')\n\nclass MemorySession extends Session {\n constructor() {\n super()\n\n this._serverAddress = null\n this._dcId = 0\n this._port = null\n this._takeoutId = null\n\n this._entities = new Set()\n this._updateStates = {}\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0\n this._serverAddress = serverAddress\n this._port = port\n }\n\n get dcId() {\n return this._dcId\n }\n\n get serverAddress() {\n return this._serverAddress\n }\n\n get port() {\n return this._port\n }\n\n get authKey() {\n return this._authKey\n }\n\n set authKey(value) {\n this._authKey = value\n }\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n }*/\n}\n\nmodule.exports = MemorySession\n","const { serializeBytes } = require('../index')\nconst { inflate } = require('pako/dist/pako_inflate')\n//CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1\n static classType = 'constructor'\n\n constructor(data) {\n this.data = data\n this.CONSTRUCTOR_ID = 0x3072cfa1\n this.classType = 'constructor'\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes()\n if (gzipped.length < data.length) {\n return gzipped\n }\n }\n return data\n }\n\n static gzip(input) {\n return Buffer.from(input)\n // TODO this usually makes it faster for large requests\n //return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input))\n }\n\n async toBytes() {\n const g = Buffer.alloc(4)\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0)\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ])\n }\n\n static async read(reader) {\n const constructor = reader.readInt(false)\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal')\n }\n return await GZIPPacked.gzip(reader.tgReadBytes())\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()))\n }\n}\n\nmodule.exports = GZIPPacked\n","const { sha1, toSignedLittleBuffer,readBufferFromBigInt, readBigIntFromBuffer } = require('../Helpers')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { sleep } = require('../Helpers')\n\nclass AuthKey {\n\n constructor(value, hash) {\n if (!hash || !value) {\n return\n }\n this._key = value\n this._hash = hash\n const reader = new BinaryReader(hash)\n this.auxHash = reader.readLong(false)\n reader.read(4)\n this.keyId = reader.readLong(false)\n }\n\n async setKey(value) {\n if (!value) {\n this._key = this.auxHash = this.keyId = this._hash = null\n return\n }\n if (value instanceof AuthKey) {\n this._key = value._key\n this.auxHash = value.auxHash\n this.keyId = value.keyId\n this._hash = value._hash\n return\n }\n this._key = value\n this._hash = await sha1(this._key)\n const reader = new BinaryReader(this._hash)\n this.auxHash = reader.readLong(false)\n reader.read(4)\n this.keyId = reader.readLong(false)\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await sleep(20)\n }\n }\n\n getKey() {\n return this._key\n }\n\n // TODO : This doesn't really fit here, it's only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields' values\n * @param newNonce\n * @param number\n * @returns {bigint}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32)\n const n = Buffer.alloc(1)\n n.writeUInt8(number, 0)\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])])\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20)\n return readBigIntFromBuffer(shaData, true, true)\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey().equals(this._key)\n }\n}\n\nmodule.exports = AuthKey\n","const Logger = require('./Logger')\nconst BinaryWriter = require('./BinaryWriter')\nconst BinaryReader = require('./BinaryReader')\nconst PromisedWebSockets = require('./PromisedWebSockets')\nconst MessagePacker = require('./MessagePacker')\nconst AsyncQueue = require('./AsyncQueue')\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","const AES = require('@cryptography/aes').default;\nconst { i2ab, ab2i } = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue)\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes)\n this._counter = bytes\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0\n } else {\n this._counter[i]++\n break\n }\n }\n }\n}\n\nclass CTR {\n constructor(key, counter) {\n\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter)\n }\n\n this._counter = counter\n\n this._remainingCounter = null\n this._remainingCounterIndex = 16\n\n this._aes = new AES(getWords(key))\n }\n\n update(plainText) {\n return this.encrypt(plainText)\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText)\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))))\n this._remainingCounterIndex = 0\n this._counter.increment()\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++]\n }\n\n return encrypted\n }\n}\n\n// endregion\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv)\n }\n}\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv)\n }\n}\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count)\n crypto.getRandomValues(bytes)\n return bytes\n}\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm\n }\n\n update(data) {\n //We shouldn't be needing new Uint8Array but it doesn't\n //work without it\n this.data = new Uint8Array(data)\n }\n\n async digest() {\n if (this.algorithm === 'sha1') {\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data))\n } else if (this.algorithm === 'sha256') {\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data))\n }\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n {name: 'PBKDF2'}, false, ['deriveBits'])\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512', salt, iterations\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm)\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2\n}\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = null) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request))\n )\n this.code = code\n this.message = message\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`\n } else {\n return ''\n }\n }\n}\n\n/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code)\n this.code = code || 303\n this.message = message || 'ERROR_SEE_OTHER'\n }\n}\n\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\nclass BadRequestError extends RPCError {\n code = 400\n message = 'BAD_REQUEST'\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401\n message = 'UNAUTHORIZED'\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403\n message = 'FORBIDDEN'\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404\n message = 'NOT_FOUND'\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406\n message = 'AUTH_KEY'\n}\n\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\nclass FloodError extends RPCError {\n code = 420\n message = 'FLOOD'\n}\n\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\nclass ServerError extends RPCError {\n code = 500 // Also witnessed as -500\n message = 'INTERNAL'\n}\n\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this \"special\" RPCError.\n */\nclass TimedOutError extends RPCError {\n code = 503 // Only witnessed as -503\n message = 'Timeout'\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n}\n","\nclass TLMessage {\n static SIZE_OVERHEAD = 12;\n static classType = \"constructor\"\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId\n this.seqNo = seqNo\n this.obj = obj\n this.classType = \"constructor\"\n }\n}\n\nmodule.exports = TLMessage\n","const TLMessage = require('./TLMessage')\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n static classType = \"constructor\"\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n\n this.CONSTRUCTOR_ID = 0x73f1f8dc\n this.messages = messages\n this.classType = \"constructor\"\n }\n\n static async fromReader(reader) {\n const messages = []\n const length = reader.readInt()\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong()\n const seqNo = reader.readInt()\n const length = reader.readInt()\n const before = reader.tellPosition()\n const obj = reader.tgReadObject()\n reader.setPosition(before + length)\n const tlMessage = new TLMessage(msgId, seqNo, obj)\n messages.push(tlMessage)\n }\n return new MessageContainer(messages)\n }\n}\n\nmodule.exports = MessageContainer\n","const MTProtoPlainSender = require('./MTProtoPlainSender')\nconst doAuthentication = require('./Authenticator')\nconst MTProtoSender = require('./MTProtoSender')\n\nclass UpdateConnectionState {\n static disconnected = -1\n static connected = 1\n static broken = 0\n\n constructor(state) {\n this.state = state\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection')\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n}\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets')\nconst AsyncQueue = require('../../extensions/AsyncQueue')\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = null\n\n constructor(ip, port, dcId, loggers) {\n this._ip = ip\n this._port = port\n this._dcId = dcId\n this._log = loggers\n this._connected = false\n this._sendTask = null\n this._recvTask = null\n this._codec = null\n this._obfuscation = null // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue()\n this._recvArray = new AsyncQueue()\n //this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets()\n }\n\n async _connect() {\n this._log.debug('Connecting')\n this._codec = new this.PacketCodecClass(this)\n await this.socket.connect(this._port, this._ip, this)\n this._log.debug('Finished connecting')\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn()\n }\n\n async connect() {\n await this._connect()\n this._connected = true\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop()\n }\n this._recvTask = this._recvLoop()\n }\n\n async disconnect() {\n this._connected = false\n await this._recvArray.push(null)\n await this.socket.close()\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected')\n }\n await this._sendArray.push(data)\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop()\n // null = sentinel value = keep trying\n if (result) {\n return result\n }\n }\n throw new Error('Not connected')\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop()\n if (!data) {\n this._sendTask = null\n return\n }\n await this._send(data)\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending')\n }\n }\n\n async _recvLoop() {\n let data\n while (this._connected) {\n try {\n data = await this._recv()\n if (!data) {\n throw new Error(\"no data received\")\n }\n } catch (e) {\n this._log.info('connection closed')\n //await this._recvArray.push()\n\n this.disconnect()\n return\n }\n await this._recvArray.push(data)\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag)\n }\n }\n\n async _send(data) {\n const encodedPacket = this._codec.encodePacket(data)\n this.socket.write(encodedPacket)\n }\n\n async _recv() {\n return await this._codec.readPacket(this.socket)\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = null\n\n async _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this)\n this.socket.write(this._obfuscation.header)\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data))\n }\n\n\n async _recv() {\n return await this._codec.readPacket(this._obfuscation)\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection\n }\n\n encodePacket(data) {\n throw new Error('Not Implemented')\n\n // Override\n }\n\n async readPacket(reader) {\n // override\n throw new Error('Not Implemented')\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n}\n","const MemorySession = require('./Memory')\nconst AuthKey = require('../crypto/AuthKey')\nconst utils = require('../Utils')\n\nconst STORAGE_KEY_BASE = 'GramJs-session-'\n\nclass StorageSession extends MemorySession {\n constructor(sessionId) {\n super()\n this._storageKey = sessionId\n this._authKeys = {}\n }\n\n async load() {\n if (!this._storageKey) {\n return\n }\n\n try {\n const json = await this._fetchFromCache()\n const { mainDcId, keys, hashes } = JSON.parse(json)\n const { ipAddress, port } = utils.getDC(mainDcId)\n\n this.setDC(mainDcId, ipAddress, port, true)\n\n Object.keys(keys).forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]){\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data)\n )\n }\n })\n } catch (err) {\n console.warn('Failed to retrieve or parse session from storage')\n console.warn(err)\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId\n this._serverAddress = serverAddress\n this._port = port\n\n delete this._authKeys[dcId]\n\n if (!skipUpdateStorage) {\n void this._updateStorage()\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey()\n }\n\n await this._updateStorage()\n\n return this._storageKey\n }\n\n get authKey() {\n throw new Error('Not supported')\n }\n\n set authKey(value) {\n throw new Error('Not supported')\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId]\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey\n\n void this._updateStorage()\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return\n }\n\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {}\n }\n\n Object.keys(this._authKeys).map((dcId) => {\n const authKey = this._authKeys[dcId]\n sessionData.keys[dcId] = authKey._key\n sessionData.hashes[dcId] = authKey._hash\n })\n\n try {\n await this._saveToCache(JSON.stringify(sessionData))\n } catch (err) {\n console.warn('Failed to update session in storage')\n console.warn(err)\n }\n }\n\n async delete() {\n try {\n return await this._delete()\n } catch (err) {\n console.warn('Failed to delete session from storage')\n console.warn(err)\n }\n }\n\n // @abstract\n async _delete() {\n throw new Error('Not Implemented')\n }\n\n // @abstract\n async _fetchFromCache() {\n throw new Error('Not Implemented')\n }\n\n // @abstract\n async _saveToCache(data) {\n throw new Error('Not Implemented')\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`\n}\n\nmodule.exports = StorageSession\n","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase())\n return result.replace(/_/g, '')\n}\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', '')\n)\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc // null#56730bcc = Null;\n])\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1 // gzip_packed\n])\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c\n const crcTable = []\n for (let n = 0; n < 256; n++) {\n c = n\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1))\n }\n crcTable[n] = c\n }\n return crcTable\n}\n\nlet crcTable = null\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable()\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf)\n }\n let crc = -1\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index]\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8)\n }\n return (crc ^ (-1)) >>> 0\n}\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/)\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`)\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line)\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction: isFunction,\n namespace: null\n }\n if (!currentConfig.constructorId) {\n\n let hexId = ''\n let args\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig).map((arg) => arg.toString()).join(' ')}`\n } else {\n args = ''\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '')\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'))\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType)\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/)\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name)\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n }*/\n return currentConfig\n}\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: null,\n useVectorId: null\n }\n\n // Special case: some types can be inferred, which makes it\n // less annoying to type. Currently the only type that can\n // be inferred is if the name is 'random_id', to which a\n // random ID will be assigned if left as None (the default)\n let canBeInferred = name === 'random_id'\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '')\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/)\n\n if (flagMatch) {\n currentConfig.isFlag = true\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/)\n\n if (vectorMatch) {\n currentConfig.isVector = true\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0)\n )\n ) {\n currentConfig.skipConstructorId = true\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig\n}\n\n\nconst parseTl = function* (content, layer, methods = [], ignoreIds = CORE_TYPES) {\n const methodInfo = (methods || []).reduce((o, m) => ({ ...o, [m.name]: m }), {})\n const objAll = []\n const objByName = {}\n const objByType = {}\n\n const file = content\n\n let isFunction = false\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//')\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex)\n }\n\n line = line.trim()\n\n if (!line) {\n continue\n }\n\n const match = line.match(/---(\\w+)---/)\n\n if (match) {\n const [, followingTypes] = match\n isFunction = followingTypes === 'functions'\n continue\n }\n\n try {\n const result = fromLine(line, isFunction)\n\n if (ignoreIds.has(result.constructorId)) {\n continue\n }\n\n objAll.push(result)\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = []\n }\n\n objByName[result.name] = result\n objByType[result.result].push(result)\n }\n } catch (e) {\n if (!e.toString().includes('vector#1cb5c415')) {\n throw e\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n //console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes'\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj\n }\n\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes(`g`)) {\n regex = new RegExp(regex.source, `g`)\n }\n\n const res = regex.exec(str)\n\n if (res) {\n matches.push(res.slice(1))\n findAll(regex, str, matches)\n }\n\n return matches\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data == 'string') {\n data = Buffer.from(data)\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`)\n }\n }\n const r = []\n let padding\n if (data.length < 254) {\n padding = (data.length + 1) % 4\n if (padding !== 0) {\n padding = 4 - padding\n }\n r.push(Buffer.from([data.length]))\n r.push(data)\n } else {\n padding = data.length % 4\n if (padding !== 0) {\n padding = 4 - padding\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]))\n r.push(data)\n }\n r.push(Buffer.alloc(padding)\n .fill(0))\n\n return Buffer.concat(r)\n\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0)\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000)\n }\n if (typeof dt == 'number') {\n const t = Buffer.alloc(4)\n t.writeInt32LE(dt, 0)\n return t\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`)\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase\n}\n","var S = new Uint8Array(256);\nvar Si = new Uint8Array(256);\nvar T1 = new Uint32Array(256);\nvar T2 = new Uint32Array(256);\nvar T3 = new Uint32Array(256);\nvar T4 = new Uint32Array(256);\nvar T5 = new Uint32Array(256);\nvar T6 = new Uint32Array(256);\nvar T7 = new Uint32Array(256);\nvar T8 = new Uint32Array(256);\nfunction computeTables() {\n var d = new Uint8Array(256);\n var t = new Uint8Array(256);\n var x2;\n var x4;\n var x8;\n var s;\n var tEnc;\n var tDec;\n var x = 0;\n var xInv = 0;\n // Compute double and third tables\n for (var i = 0; i < 256; i++) {\n d[i] = i << 1 ^ (i >> 7) * 283;\n t[d[i] ^ i] = i;\n }\n for (; !S[x]; x ^= x2 || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n S[x] = s;\n Si[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n T1[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T2[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T3[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T4[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T5[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T6[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T7[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T8[s] = tDec = tDec << 24 ^ tDec >>> 8;\n xInv = t[xInv] || 1;\n }\n}\n\n/**\n * Gets a uint32 from string in big-endian order order\n */\nfunction s2i(str, pos) {\n return (str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3));\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Helper function for transforming string key to Uint32Array\n */\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n if (typeof key === 'string') {\n if (key.length % 4 !== 0)\n for (var i = key.length % 4; i <= 4; i++)\n key += '\\0x00';\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4)\n buf[i / 4] = s2i(key, i);\n return buf;\n }\n if (key instanceof Uint8Array) {\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4) {\n buf[i / 4] = (key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]);\n }\n return buf;\n }\n throw new Error('Unable to create 32-bit words');\n}\nfunction xor(left, right, to) {\n if (to === void 0) { to = left; }\n for (var i = 0; i < left.length; i++)\n to[i] = left[i] ^ right[i];\n}\n\ncomputeTables();\n/**\n * Low-level AES Cipher\n */\nvar AES = /** @class */ (function () {\n function AES(_key) {\n var key = getWords(_key);\n if (key.length !== 4 && key.length !== 6 && key.length !== 8) {\n throw new Error('Invalid key size');\n }\n this.encKey = new Uint32Array(4 * key.length + 28);\n this.decKey = new Uint32Array(4 * key.length + 28);\n this.encKey.set(key);\n var rcon = 1;\n var i = key.length;\n var tmp;\n // schedule encryption keys\n for (; i < 4 * key.length + 28; i++) {\n tmp = this.encKey[i - 1];\n // apply sbox\n if (i % key.length === 0 || (key.length === 8 && i % key.length === 4)) {\n tmp = S[tmp >>> 24] << 24 ^ S[(tmp >> 16) & 255] << 16 ^ S[(tmp >> 8) & 255] << 8 ^ S[tmp & 255];\n // shift rows and add rcon\n if (i % key.length === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ (rcon << 24);\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n this.encKey[i] = this.encKey[i - key.length] ^ tmp;\n }\n // schedule decryption keys\n for (var j = 0; i; j++, i--) {\n tmp = this.encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n this.decKey[j] = tmp;\n }\n else {\n this.decKey[j] = (T5[S[tmp >>> 24]]\n ^ T6[S[(tmp >> 16) & 255]]\n ^ T7[S[(tmp >> 8) & 255]]\n ^ T8[S[tmp & 255]]);\n }\n }\n }\n AES.prototype.encrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.encKey[0];\n var b = message[1] ^ this.encKey[1];\n var c = message[2] ^ this.encKey[2];\n var d = message[3] ^ this.encKey[3];\n var rounds = this.encKey.length / 4 - 2;\n var k = 4;\n var a2;\n var b2;\n var c2;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T1[a >>> 24] ^ T2[(b >> 16) & 255] ^ T3[(c >> 8) & 255] ^ T4[d & 255] ^ this.encKey[k];\n b2 = T1[b >>> 24] ^ T2[(c >> 16) & 255] ^ T3[(d >> 8) & 255] ^ T4[a & 255] ^ this.encKey[k + 1];\n c2 = T1[c >>> 24] ^ T2[(d >> 16) & 255] ^ T3[(a >> 8) & 255] ^ T4[b & 255] ^ this.encKey[k + 2];\n d = T1[d >>> 24] ^ T2[(a >> 16) & 255] ^ T3[(b >> 8) & 255] ^ T4[c & 255] ^ this.encKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n // console.log(a, b, c, d);\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[i] = (S[a >>> 24] << 24\n ^ S[(b >> 16) & 255] << 16\n ^ S[(c >> 8) & 255] << 8\n ^ S[d & 255]\n ^ this.encKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n AES.prototype.decrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.decKey[0];\n var b = message[3] ^ this.decKey[1];\n var c = message[2] ^ this.decKey[2];\n var d = message[1] ^ this.decKey[3];\n var rounds = this.decKey.length / 4 - 2;\n var a2;\n var b2;\n var c2;\n var k = 4;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T5[a >>> 24] ^ T6[(b >> 16) & 255] ^ T7[(c >> 8) & 255] ^ T8[d & 255] ^ this.decKey[k];\n b2 = T5[b >>> 24] ^ T6[(c >> 16) & 255] ^ T7[(d >> 8) & 255] ^ T8[a & 255] ^ this.decKey[k + 1];\n c2 = T5[c >>> 24] ^ T6[(d >> 16) & 255] ^ T7[(a >> 8) & 255] ^ T8[b & 255] ^ this.decKey[k + 2];\n d = T5[d >>> 24] ^ T6[(a >> 16) & 255] ^ T7[(b >> 8) & 255] ^ T8[c & 255] ^ this.decKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[3 & -i] = (Si[a >>> 24] << 24\n ^ Si[(b >> 16) & 255] << 16\n ^ Si[(c >> 8) & 255] << 8\n ^ Si[d & 255]\n ^ this.decKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n return AES;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE = /** @class */ (function () {\n function AES_IGE(key, iv, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.key = getWords(key);\n this.iv = getWords(iv);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var prevX = this.iv.subarray(this.blockSize, this.iv.length);\n var prevY = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = text.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.encrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n cipherText[j] = y[k];\n }\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n var cipherText = getWords(message);\n var text = buf || new Uint32Array(cipherText.length);\n var prevY = this.iv.subarray(this.blockSize, this.iv.length);\n var prevX = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = cipherText.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.decrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n text[j] = y[k];\n }\n return text;\n };\n return AES_IGE;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE$1 = /** @class */ (function () {\n function AES_IGE(key, counter, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.offset = 0;\n this.key = getWords(key);\n this.counter = getWords(counter);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n if (this.counter.length !== 4) {\n throw new Error('AES-CTR mode counter must be 16 bytes length');\n }\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var offset = this.offset;\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = this.cipher.encrypt(this.counter);\n for (var j = i, k = offset; j < text.length && k < this.blockSize; j++, k++)\n cipherText[j] = x[k] ^ text[j];\n if (text.length - i >= this.blockSize)\n this.incrementCounter();\n if (offset) {\n i -= offset;\n offset = 0;\n }\n }\n this.offset = (this.offset + (text.length % 4)) % 4;\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n return this.encrypt(message, buf);\n };\n AES_IGE.prototype.incrementCounter = function () {\n // increment counter\n for (var carry = this.counter.length - 1; carry >= 0; carry--) {\n if (++this.counter[carry] < 0xFFFFFFFF)\n break; // If overflowing, it'll be 0 and we'll have to continue propagating the carry\n }\n };\n return AES_IGE;\n}());\n\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\n","let _level = null\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug']\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug'\n }\n\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n if (!this.isBrowser) {\n this.colors = {\n start: '\\x1b[2m',\n warn: '\\x1b[35m',\n info: '\\x1b[33m',\n debug: '\\x1b[36m',\n error: '\\x1b[31m',\n end: '\\x1b[0m',\n }\n } else {\n this.colors = {\n start: '%c',\n warn: 'color : #ff00ff',\n info: 'color : #ffff00',\n debug: 'color : #00ffff',\n error: 'color : #ff0000',\n end: '',\n }\n }\n this.messageFormat = '[%t] [%l] - [%m]'\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level))\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n this._log('warn', message, this.colors.warn)\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info)\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug)\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n this._log('error', message, this.colors.error)\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message)\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level){\n return\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n console.log(color + this.format(message, level) + this.colors.end)\n } else {\n console.log(this.colors.start + this.format(message, level), color)\n }\n } else {\n\n }\n }\n}\n\nmodule.exports = Logger\n","const { RPCError, InvalidDCError, FloodError, BadRequestError } = require('./RPCBaseErrors')\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0)\n super(`A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request))\n this.message = `A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request)\n this.seconds = seconds\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0)\n super(`The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request))\n this.message = `The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request)\n this.newDc = newDc\n }\n}\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0)\n super(`Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request))\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request)\n this.codeLength = codeLength\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n]\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n EmailUnconfirmedError\n}\n","class Session {\n constructor() {\n\n }\n\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n }*/\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented')\n }\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented')\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /*CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /*CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /*CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /*CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n /*CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented')\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /*CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /*CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /*CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer])\n }\n\n getValue() {\n return this._stream\n }\n}\n\nmodule.exports = BinaryWriter\n","const TLMessage = require('./TLMessage')\nconst RPCResult = require('./RPCResult')\nconst MessageContainer = require('./MessageContainer')\nconst GZIPPacked = require('./GZIPPacked')\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n}\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n}\n","const { RpcError } = require('../index').constructors\nconst GZIPPacked = require('./GZIPPacked')\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n static classType = \"constructor\"\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01\n this.reqMsgId = reqMsgId\n this.body = body\n this.error = error\n this.classType = \"constructor\"\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong()\n const innerCode = reader.readInt(false)\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, null, RpcError.fromReader(reader))\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data)\n }\n reader.seek(-4)\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), null)\n }\n}\n\nmodule.exports = RPCResult\n","const api = require('./api')\nconst LAYER = 121\nconst tlobjects = {}\n\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects\n}\n","const Mutex = require('async-mutex').Mutex\nconst mutex = new Mutex()\n\nconst WebSocketClient = require('websocket').w3cwebsocket\n\nconst closeError = new Error('WebSocket was closed')\n\nclass PromisedWebSockets {\n constructor() {\n /*CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = null\n this.closed = true\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0)\n while (true) {\n const thisTime = await this.read(number)\n readData = Buffer.concat([readData, thisTime])\n number = number - thisTime.length\n if (!number) {\n return readData\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError\n }\n await this.canRead\n if (this.closed) {\n throw closeError\n }\n const toReturn = this.stream.slice(0, number)\n this.stream = this.stream.slice(number)\n if (this.stream.length === 0) {\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n }\n\n return toReturn\n }\n\n async readAll() {\n if (this.closed || !await this.canRead) {\n throw closeError\n }\n const toReturn = this.stream\n this.stream = Buffer.alloc(0)\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n\n return toReturn\n }\n\n getWebSocketLink(ip, port) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`\n } else {\n return `ws://${ip}:${port}/apiws`\n }\n }\n\n async connect(port, ip) {\n this.stream = Buffer.alloc(0)\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve\n })\n this.closed = false\n this.website = this.getWebSocketLink(ip, port)\n this.client = new WebSocketClient(this.website, 'binary')\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive()\n resolve(this)\n }\n this.client.onerror = (error) => {\n reject(error)\n }\n this.client.onclose = () => {\n this.resolveRead(false)\n this.closed = true\n }\n //CONTEST\n // Seems to not be working, at least in a web worker\n self.addEventListener('offline', async () => {\n await this.close()\n this.resolveRead(false)\n })\n })\n }\n\n write(data) {\n if (this.closed) {\n throw closeError\n }\n this.client.send(data)\n }\n\n async close() {\n await this.client.close()\n this.closed = true\n }\n\n async receive() {\n this.client.onmessage = async (message) => {\n const release = await mutex.acquire()\n try {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer())\n this.stream = Buffer.concat([this.stream, data])\n this.resolveRead(true)\n } finally {\n release()\n }\n }\n }\n}\n\nmodule.exports = PromisedWebSockets\n","const MessageContainer = require('../tl/core/MessageContainer')\nconst TLMessage = require('../tl/core/TLMessage')\nconst BinaryWriter = require('../extensions/BinaryWriter')\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state\n this._queue = []\n this._pendingStates = []\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve\n }))\n this._log = logger\n }\n\n values() {\n return this._queue\n }\n\n append(state) {\n this._queue.push(state)\n this.setReady(true)\n\n if (state) {\n this._pendingStates.push(state)\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {})\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state)\n })\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state)\n }\n this.setReady(true)\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve\n }))\n await this._ready\n }\n if (!this._queue[this._queue.length - 1]) {\n this._queue = []\n return\n }\n let data\n let buffer = new BinaryWriter(Buffer.alloc(0))\n\n const batch = []\n let size = 0\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift()\n size += state.data.length + TLMessage.SIZE_OVERHEAD\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId\n if (state.after) {\n afterId = state.after.msgId\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n )\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className || state.request.constructor.name}`)\n batch.push(state)\n continue\n }\n if (batch.length) {\n this._queue.unshift(state)\n break\n }\n this._log.warn(`Message payload for ${state.request.className || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`)\n state.reject('Request Payload is too big')\n size = 0\n continue\n }\n if (!batch.length) {\n return null\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8)\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0)\n b.writeInt32LE(batch.length, 4)\n data = Buffer.concat([b, buffer.getValue()])\n buffer = new BinaryWriter(Buffer.alloc(0))\n const containerId = await this._state.writeDataAsMessage(\n buffer, data, false,\n )\n for (const s of batch) {\n s.containerId = containerId\n }\n }\n\n data = buffer.getValue()\n return { batch, data }\n }\n\n rejectAll() {\n this._pendingStates.forEach((requestState) => {\n requestState.reject(new Error('Disconnect'))\n })\n }\n}\n\nmodule.exports = MessagePacker\n","class AsyncQueue {\n constructor() {\n this._queue = []\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve\n })\n this.canPush = true\n }\n\n async push(value) {\n await this.canPush\n this._queue.push(value)\n this.resolveGet(true)\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve\n })\n }\n\n async pop() {\n await this.canGet\n const returned = this._queue.pop()\n this.resolvePush(true)\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve\n })\n return returned\n }\n}\n\nmodule.exports = AsyncQueue\n","const MtProtoPlainSender = require('./MTProtoPlainSender')\nconst MTProtoState = require('./MTProtoState')\nconst Helpers = require('../Helpers')\nconst AuthKey = require('../crypto/AuthKey')\nconst doAuthentication = require('./Authenticator')\nconst RPCResult = require('../tl/core/RPCResult')\nconst MessageContainer = require('../tl/core/MessageContainer')\nconst GZIPPacked = require('../tl/core/GZIPPacked')\nconst RequestState = require('./RequestState')\nconst { MsgsAck, upload, MsgsStateInfo, Pong } = require('../tl').constructors\nconst MessagePacker = require('../extensions/MessagePacker')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { UpdateConnectionState } = require(\"./index\");\nconst { BadMessageError } = require(\"../errors/Common\")\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors\nconst { SecurityError } = require('../errors/Common')\nconst { InvalidBufferError } = require('../errors/Common')\nconst { LogOut } = require('../tl').requests.auth\nconst { RPCMessageToError } = require('../errors')\nconst { TypeNotFoundError } = require('../errors/Common')\n\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: null,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: null,\n authKeyCallback: null,\n updateCallback: null,\n autoReconnectCallback: null,\n isMainSender: null,\n onConnectionBreak: null,\n }\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts }\n this._connection = null\n this._log = args.logger\n this._dcId = args.dcId\n this._retries = args.retries\n this._delay = args.delay\n this._autoReconnect = args.autoReconnect\n this._connectTimeout = args.connectTimeout\n this._authKeyCallback = args.authKeyCallback\n this._updateCallback = args.updateCallback\n this._autoReconnectCallback = args.autoReconnectCallback\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false\n this._reconnecting = false\n this._disconnected = true\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = null\n this._recv_loop_handle = null\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey()\n this._state = new MTProtoState(this.authKey, this._log)\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log)\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {}\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set()\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = []\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n }\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!')\n return false\n }\n this._connection = connection\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect()\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected))\n }\n break\n } catch (err) {\n if (this._updateCallback && attempt===0){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected))\n }\n this._log.error('WebSocket connection failed attempt: ' + (attempt + 1))\n await Helpers.sleep(this._delay)\n }\n }\n }\n\n isConnected() {\n return this._user_connected\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n await this._disconnect()\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected')\n }\n //CONTEST\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n }*/\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection))\n await this._connection.connect()\n this._log.debug('Connection success!')\n //process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log)\n this._log.debug('New auth_key attempt ...')\n const res = await doAuthentication(plain, this._log)\n this._log.debug('Generated new auth_key successfully')\n await this.authKey.setKey(res.authKey)\n\n this._state.time_offset = res.timeOffset\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId)\n }\n } else {\n this._log.debug('Already have an auth key ...')\n }\n this._user_connected = true\n this._reconnecting = false\n\n this._log.debug('Starting send loop')\n this._send_loop_handle = this._sendLoop()\n\n this._log.debug('Starting receive loop')\n this._recv_loop_handle = this._recvLoop()\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()))\n }\n\n async _disconnect(error = null) {\n this._send_queue.rejectAll()\n\n if (this._connection === null) {\n this._log.info('Not disconnecting (already have no connection)')\n return\n }\n if (this._updateCallback){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected))\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()))\n this._user_connected = false\n this._log.debug('Closing current connection...')\n await this._connection.disconnect()\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log)\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }))\n this._send_queue.append(ack)\n this._last_acks.push(ack)\n this._pending_ack.clear()\n }\n this._log.debug('Waiting for messages to send...'+this._reconnecting)\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get()\n\n if (this._reconnecting) {\n return\n }\n\n if (!res) {\n continue\n }\n let data = res.data\n const batch = res.batch\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`)\n\n data = await this._state.encryptMessageData(data)\n\n try {\n await this._connection.send(data)\n } catch (e) {\n this._log.error(e)\n this._log.info('Connection closed while sending data')\n return\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent')\n }\n }\n\n async _recvLoop() {\n let body\n let message\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...')\n try {\n body = await this._connection.recv()\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data')\n this.reconnect()\n return\n }\n try {\n message = await this._state.decryptMessageData(body)\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`)\n continue\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`)\n continue\n } else if (e instanceof InvalidBufferError) {\n this._log.info('Broken authorization key; resetting')\n if (this._updateCallback && this._isMainSender){\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken))\n } else if (this._onConnectionBreak && !this._isMainSender){\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId)\n }\n\n // We don't really need to do this if we're going to sign in again\n /*await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n }*/\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return\n } else {\n this._log.error('Unhandled error while receiving data')\n this._log.error(e)\n this.reconnect()\n return\n }\n }\n try {\n await this._processMessage(message)\n } catch (e) {\n this._log.error('Unhandled error while receiving data')\n this._log.error(e)\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId)\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID]\n if (!handler) {\n handler = this._handleUpdate.bind(this)\n }\n\n await handler(message)\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId]\n if (state) {\n delete this._pending_state[msgId]\n return [state]\n }\n\n const toPop = []\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId)\n }\n }\n\n if (toPop.length) {\n const temp = []\n for (const x of toPop) {\n temp.push(this._pending_state[x])\n delete this._pending_state[x]\n }\n return temp\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack]\n }\n }\n\n return []\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const RPCResult = message.obj\n const state = this._pending_state[RPCResult.reqMsgId]\n if (state) {\n delete this._pending_state[RPCResult.reqMsgId]\n }\n this._log.debug(`Handling RPC result for message ${RPCResult.reqMsgId}`)\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(RPCResult.body)\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File')\n }\n } catch (e) {\n this._log.error(e)\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${RPCResult.body}`)\n return\n } else {\n throw e\n }\n }\n }\n if (RPCResult.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(RPCResult.error, state.request)\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })))\n state.reject(error)\n } else {\n const reader = new BinaryReader(RPCResult.body)\n const read = state.request.readResult(reader)\n state.resolve(read)\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container')\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage)\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data')\n const reader = new BinaryReader(message.obj.data)\n message.obj = reader.tgReadObject()\n await this._processMessage(message)\n }\n\n async _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`)\n return\n }\n this._log.debug('Handling update ' + message.obj.className)\n if (this._updateCallback) {\n this._updateCallback(message.obj)\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handlePong(message) {\n const pong = message.obj\n this._log.debug(`Handling pong for message ${pong.msgId}`)\n const state = this._pending_state[pong.msgId]\n delete this._pending_state[pong.msgId]\n\n // Todo Check result\n if (state) {\n state.resolve(pong)\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleBadServerSalt(message) {\n const badSalt = message.obj\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`)\n this._state.salt = badSalt.newServerSalt\n const states = this._popStates(badSalt.badMsgId)\n this._send_queue.extend(states)\n this._log.debug(`${states.length} message(s) will be resent`)\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleBadNotification(message) {\n const badMsg = message.obj\n const states = this._popStates(badMsg.badMsgId)\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`)\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const to = this._state.updateTimeOffset(message.msgId)\n this._log.info(`System clock is wrong, set time offset to ${to}s`)\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16\n } else {\n\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode))\n }\n\n return\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states)\n this._log.debug(`${states.length} messages will be resent due to bad msg`)\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId\n this._log.debug(`Handling detailed info for message ${msgId}`)\n this._pending_ack.add(msgId)\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId\n this._log.debug(`Handling new detailed info for message ${msgId}`)\n this._pending_ack.add(msgId)\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created')\n this._state.salt = message.obj.serverSalt\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleAck(message) {\n const ack = message.obj\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`)\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId]\n if (state && state.request instanceof LogOut) {\n delete this._pending_state[msgId]\n state.resolve(true)\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`)\n const state = this._pending_state[message.msgId]\n\n if (state) {\n delete this._pending_state[message]\n state.resolve(message.obj)\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1).repeat(message.obj.msgIds))),\n )\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleMsgAll(message) {\n }\n\n async reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info(\"Started reconnecting\")\n this._reconnect()\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...')\n try {\n await this.disconnect()\n } catch (err) {\n this._log.warn(err)\n }\n\n this._send_queue.append(null)\n this._state.reset()\n\n await this.connect(this._connection, true)\n\n this._reconnecting = false\n // uncomment this if you want to resend\n //this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {}\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback()\n }\n }\n}\n\nmodule.exports = MTProtoSender\n","/**\n * This module contains the class used to communicate with Telegram's servers\n * in plain text, when no authorization key has been created yet.\n */\nconst Helpers = require('../Helpers')\nconst MTProtoState = require('./MTProtoState')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { InvalidBufferError } = require('../errors/Common')\nconst BigInt = require('big-integer')\nconst { toSignedLittleBuffer } = require(\"../Helpers\")\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState(connection, loggers)\n this._connection = connection\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n\n let body = request.getBytes()\n let msgId = this._state._getNewMsgId()\n const m = toSignedLittleBuffer(msgId, 8)\n const b = Buffer.alloc(4)\n b.writeInt32LE(body.length, 0)\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body])\n\n await this._connection.send(res)\n body = await this._connection.recv()\n if (body.length < 8) {\n throw new InvalidBufferError(body)\n }\n const reader = new BinaryReader(body)\n const authKeyId = reader.readLong()\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId')\n }\n msgId = reader.readLong()\n if (msgId.eq(BigInt(0))) {\n throw new Error('Bad msgId')\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n const length = reader.readInt()\n if (length <= 0) {\n throw new Error('Bad length')\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn't used for anything else after this, it's unnecessary.\n */\n return reader.tgReadObject()\n }\n\n}\n\nmodule.exports = MTProtoPlainSender\n","const Helpers = require('../Helpers')\nconst IGE = require('../crypto/IGE')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst GZIPPacked = require('../tl/core/GZIPPacked')\nconst { TLMessage } = require('../tl/core')\nconst { SecurityError, InvalidBufferError } = require('../errors/Common')\nconst { InvokeAfterMsg } = require('../tl').requests\nconst BigInt = require('big-integer')\nconst { toSignedLittleBuffer,readBufferFromBigInt } = require(\"../Helpers\")\nconst { readBigIntFromBuffer } = require(\"../Helpers\")\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey\n this._log = loggers\n this.timeOffset = 0\n this.salt = 0\n\n this.id = this._sequence = this._lastMsgId = null\n this.reset()\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true)\n this._sequence = 0\n this._lastMsgId = BigInt(0)\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId()\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha256a , sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey]))\n ])\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)])\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)])\n return { key, iv }\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId()\n const seqNo = this._getSeqNo(contentRelated)\n let body\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data)\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes())\n }\n const s = Buffer.alloc(4)\n s.writeInt32LE(seqNo, 0)\n const b = Buffer.alloc(4)\n b.writeInt32LE(body.length, 0)\n const m = toSignedLittleBuffer(msgId, 8)\n buffer.write(Buffer.concat([m, s, b]))\n buffer.write(body)\n return msgId\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey()\n const s = toSignedLittleBuffer(this.salt,8)\n const i = toSignedLittleBuffer(this.id,8)\n data = Buffer.concat([Buffer.concat([s,i]), data])\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12)\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey().slice(88, 88 + 32), data, padding]))\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24)\n\n const { iv, key } = await this._calcKey(this.authKey.getKey(), msgKey, true)\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8)\n return Buffer.concat([keyId, msgKey, new IGE(key,iv).encryptIge(Buffer.concat([data, padding]))])\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body)\n }\n\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8))\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key')\n }\n\n const msgKey = body.slice(8, 24)\n const { iv, key } = await this._calcKey(this.authKey.getKey(), msgKey, false)\n body = new IGE(key,iv).decryptIge(body.slice(24))\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey().slice(96, 96 + 32), body]))\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one')\n }\n\n const reader = new BinaryReader(body)\n reader.readLong() // removeSalt\n const serverId = reader.readLong()\n if (serverId !== this.id) {\n // throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong()\n const remoteSequence = reader.readInt()\n reader.readInt() // msgLen for the inner object, padding ignored\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject()\n\n return new TLMessage(remoteMsgId, remoteSequence, obj)\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9)\n let newMsgId = (BigInt(Math.floor(now)).shiftLeft(BigInt(32))).or(BigInt(nanoseconds).shiftLeft(BigInt(2)))\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4))\n }\n this._lastMsgId = newMsgId\n return newMsgId\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId()\n const old = this.timeOffset\n const now = Math.floor(new Date().getTime() / 1000)\n const correct = correctMsgId.shiftRight(BigInt(32))\n this.timeOffset = correct - now\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0)\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n )\n }\n\n return this.timeOffset\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1\n this._sequence += 1\n return result\n } else {\n return this._sequence * 2\n }\n }\n}\n\nmodule.exports = MTProtoState\n","const Helpers = require(\"../Helpers\");\n\nconst {IGE:aes_ige} = require('@cryptography/aes');\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new aes_ige(key,iv);\n }\n\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n encryptIge(plainText) {\n const padding = plainText.length % 16\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)])\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n\n\n }\n\n}\n\nmodule.exports = IGENEW\n","const BigInt = require('big-integer')\nconst IGE = require('../crypto/IGE')\nconst AuthKey = require('../crypto/AuthKey')\nconst Factorizator = require('../crypto/Factorizator')\nconst RSA = require('../crypto/RSA')\nconst Helpers = require('../Helpers')\nconst { constructors, requests } = require('../tl')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst { SecurityError } = require(\"../errors/Common\")\n\n/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\nasync function doAuthentication(sender, log) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16)\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true)\n\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce: nonce }))\n log.debug('Starting authKey generation step 1')\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`Step 1 answer was ${resPQ}`)\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server')\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true)\n log.debug('Finished authKey generation step 1')\n log.debug('Starting authKey generation step 2')\n // Step 2 sending: DH Exchange\n let { p, q } = Factorizator.factorize(pq)\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p)\n q = Helpers.getByteArray(q)\n\n bytes = Helpers.generateRandomBytes(32)\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true)\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p: p,\n q: q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce: newNonce,\n })\n\n // sha_digest + data + random_bytes\n let cipherText = null\n let targetFingerprint = null\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes())\n if (cipherText !== null && cipherText !== undefined) {\n targetFingerprint = fingerprint\n break\n }\n }\n if (cipherText === null || cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints')\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: p,\n q: q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n )\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk || serverDhParams instanceof constructors.ServerDHParamsFail)) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`)\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server')\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server')\n }\n\n if (serverDhParams instanceof constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32).slice(4, 20))\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true)\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server')\n }\n }\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`)\n }\n log.debug('Finished authKey generation step 2')\n log.debug('Starting authKey generation step 3')\n\n // Step 3 sending: Complete DH Exchange\n const { key, iv } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce)\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch')\n }\n const ige = new IGE(key,iv)\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer)\n const reader = new BinaryReader(plainTextAnswer)\n reader.read(20) // hash sum\n const serverDhInner = reader.tgReadObject()\n if (!(serverDhInner instanceof constructors.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`)\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer')\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 3 Invalid server nonce in encrypted answer')\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false)\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false)\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000)\n const b = Helpers.readBigIntFromBuffer(Helpers.generateRandomBytes(256), false, false)\n const gb = Helpers.modExp(BigInt(serverDhInner.g), b, dhPrime)\n const gab = Helpers.modExp(ga, b, dhPrime)\n\n // Prepare client DH Inner Data\n const clientDhInner = new constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes()\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner])\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed)\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n )\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail]\n if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {\n throw new Error(`Step 3.1 answer was ${dhGen}`)\n }\n const { name } = dhGen.constructor\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`)\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(`Step 3 invalid ${name} server nonce from server`)\n }\n const authKey = new AuthKey()\n await authKey.setKey(Helpers.getByteArray(gab))\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor)\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber)\n const dhHash = dhGen[`newNonceHash${nonceNumber}`]\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash')\n }\n\n if (!(dhGen instanceof constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`)\n }\n log.debug('Finished authKey generation step 3')\n\n return { authKey, timeOffset }\n}\n\n\nmodule.exports = doAuthentication\n","const BigInt = require('big-integer')\nconst { modExp } = require('../Helpers')\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(BigInt.zero)) {\n let temp = b\n b = a.remainder(b)\n a = temp\n }\n return a\n }\n\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n static factorize(pq) {\n if (pq.remainder(2).equals(BigInt.zero)) {\n return { p: BigInt(2), q: pq.divide(BigInt(2)) }\n }\n let y = BigInt.randBetween(BigInt(1),pq.minus(1))\n const c = BigInt.randBetween(BigInt(1),pq.minus(1))\n const m = BigInt.randBetween(BigInt(1),pq.minus(1))\n\n let g = BigInt.one\n let r = BigInt.one\n let q = BigInt.one\n let x = BigInt.zero\n let ys = BigInt.zero\n let k\n\n while (g.eq(BigInt.one)) {\n x = y\n for (let i = 0; BigInt(i).lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c).remainder(pq)\n }\n k = BigInt.zero\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n\n ys = y\n let condition = BigInt.min(m, r.minus(k))\n for (let i = 0; BigInt(i).lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c).remainder(pq)\n q = q.multiply(x.minus(y).abs()).remainder(pq)\n }\n g = Factorizator.gcd(q, pq)\n k = k.add(m)\n }\n\n r = r.multiply(2)\n }\n\n\n if (g.eq(pq)) {\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c).remainder(pq)\n g = Factorizator.gcd(x.minus(ys).abs(), pq)\n\n if (g.greater(1)) {\n break\n }\n }\n }\n const p = g\n q = pq.divide(g)\n return p < q ? { p: p, q: q } : { p: q, q: p }\n }\n}\n\nmodule.exports = Factorizator\n","const { readBufferFromBigInt } = require('../../Helpers')\nconst { Connection, PacketCodec } = require('./Connection')\nconst BigInt = require('big-integer')\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex')\n static obfuscateTag = Buffer.from('efefefef', 'hex')\n\n constructor(props) {\n super(props)\n this.tag = AbridgedPacketCodec.tag\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag\n }\n\n encodePacket(data) {\n let length = data.length >> 2\n if (length < 127) {\n const b = Buffer.alloc(1)\n b.writeUInt8(length, 0)\n length = b\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)])\n }\n return Buffer.concat([length, data])\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1)\n let length = readData[0]\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0)\n }\n\n return await reader.read(length << 2)\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n}\n","const { generateRandomBytes } = require('../../Helpers')\nconst { ObfuscatedConnection } = require('./Connection')\nconst { AbridgedPacketCodec } = require('./TCPAbridged')\nconst CTR = require('../../crypto/CTR')\n\nclass ObfuscatedIO {\n header = null\n\n constructor(connection) {\n this.connection = connection.socket\n const res = this.initHeader(connection.PacketCodecClass)\n this.header = res.random\n\n this._encrypt = res.encryptor\n this._decrypt = res.decryptor\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')]\n let random\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64)\n if (random[0] !== 0xef && !(random.slice(4, 8).equals(Buffer.alloc(4)))) {\n let ok = true\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false\n break\n }\n }\n if (ok) {\n break\n }\n }\n }\n random = random.toJSON().data\n\n const randomReversed = Buffer.from(random.slice(8, 56)).reverse()\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40))\n const encryptIv = Buffer.from(random.slice(40, 56))\n const decryptKey = Buffer.from(randomReversed.slice(0, 32))\n const decryptIv = Buffer.from(randomReversed.slice(32, 48))\n const encryptor = new CTR(encryptKey, encryptIv)\n const decryptor = new CTR(decryptKey, decryptIv)\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ])\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random).slice(56, 64)),Buffer.from(random.slice(64)) ,\n ])\n return { random, encryptor, decryptor }\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n)\n return this._decrypt.encrypt(data)\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data))\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO\n PacketCodecClass = AbridgedPacketCodec\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n}\n\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n\n uint8[i++] = int >>> 24;\n uint8[i++] = (int >> 16) & 0xFF;\n uint8[i++] = (int >> 8) & 0xFF;\n uint8[i++] = int & 0xFF;\n }\n\n return uint8.buffer;\n}\n\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === 'string') {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += '\\0x00';\n\n const buf = new Uint32Array(key.length / 4);\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#23ab23d2 flags:# id:InputDocument ttl_seconds:flags.0?int = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#f4e096c3 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#27d69997 flags:# big:flags.0?true peer:InputPeer volume_id:long local_id:int = InputFileLocation;\ninputStickerSetThumb#dbaeae9 stickerset:InputStickerSet volume_id:long local_id: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 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#69d3ab26 flags:# has_video:flags.0?true photo_id:long photo_small:FileLocation photo_big:FileLocation 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 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 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#1b7c9db3 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:ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int = ChatFull;\nchannelFull#f0e6672a 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: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 = 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#d20b9f3c flags:# has_video:flags.0?true photo_small:FileLocation photo_big:FileLocation dc_id:int = ChatPhoto;\nmessageEmpty#83e5de54 id:int = Message;\nmessage#58ae39c9 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 = Message;\nmessageService#286fa604 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 = 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;\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#77bfb61b type:string location:FileLocation w:int h:int size:int = PhotoSize;\nphotoCachedSize#e9a734fa type:string location:FileLocation w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#5aa86a51 type:string location:FileLocation 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 geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#e1746d0a text:string = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\nuserFull#edf17c12 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 = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#9a65ea1f chat_id:int user_id:int action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#12b9417b user_id:int phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#54826690 flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#e73547e1 flags:# query_id:long user_id:int peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#42f88f2c poll_id:long user_id:int options:Vector = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelParticipant#65d2b464 flags:# channel_id:int date:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant qts:int = Update;\nupdateChannelMessageForwards#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#ff2abe9f flags:# channel_id:int top_msg_id:flags.0?int user_id:int action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#2296d2c8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShortChatMessage#402d5dbb flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#11f1331c flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#13d6dd27 id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteEmpty#69df3769 = ExportedChatInvite;\nchatInviteExported#fc2e05bc link:string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#eeb46f27 flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumb:flags.4?PhotoSize thumb_dc_id:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#1c0facaf flags:# left:flags.0?true user_id:int kicked_by:int date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#c3c6796b user_id:int = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#f56ee2a8 count:int participants:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#d0d9b163 participant:ChannelParticipant users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#2e0709a5 hash:int gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#58fffcd0 pos:int user_id:int score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#c30aa358 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#3f56aea3 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#500911e1 flags:# date:int bot_id:int invoice:Invoice provider_id:int info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsAndroidPay#ca05d50e payment_token:DataJSON google_transaction_id:string = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#cac943f2 hash:long bot_id:int domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#5108d648 hash:int sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#badcc1a3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfileLocationToBeDeprecated#bc7fc6cd volume_id:long local_id:int = FileLocation;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\n// Some unused classes were removed below this line\nvideoSize#e831c556 flags:# type:string location:FileLocation w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nmessages.discussionMessage#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector = Bool;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#d4982db5 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#df7534c peer:InputPeer = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = channels.ChannelParticipants;\nchannels.getParticipant#546dd7a6 channel:InputChannel user_id:InputUser = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#72796912 channel:InputChannel user_id:InputUser banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#99f09745 msg_id:int = payments.PaymentForm;\npayments.getPaymentReceipt#a092a980 msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#770a8e74 flags:# save:flags.0?true msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#2b8879b3 flags:# msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 121\n`;","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const Logger = require('../extensions/Logger')\nconst { sleep } = require('../Helpers')\nconst errors = require('../errors')\nconst MemorySession = require('../sessions/Memory')\nconst Helpers = require('../Helpers')\nconst { BinaryWriter } = require('../extensions')\nconst utils = require('../Utils')\nconst Session = require('../sessions/Abstract')\nconst os = require('os')\nconst { LAYER } = require('../tl/AllTLObjects')\nconst { constructors, requests } = require('../tl')\nconst MTProtoSender = require('../network/MTProtoSender')\nconst { UpdateConnectionState } = require(\"../network\")\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')\nconst { authFlow, checkAuthorization } = require('./auth')\nconst { downloadFile } = require('./downloadFile')\nconst { uploadFile } = require('./uploadFile')\nconst { updateTwoFaSettings } = require('./2fa')\n\nconst DEFAULT_DC_ID = 2\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org'\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]'\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's']\n\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: null,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: null,\n systemVersion: null,\n appVersion: null,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n }\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (apiId === undefined || apiHash === undefined) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md')\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts }\n this.apiId = apiId\n this.apiHash = apiHash\n this._useIPV6 = args.useIPV6\n // this._entityCache = new Set()\n if (typeof args.baseLogger == 'string') {\n this._log = new Logger()\n } else {\n this._log = args.baseLogger\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented')\n } catch (e) {\n session = new MemorySession()\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance')\n }\n\n this.floodSleepLimit = args.floodSleepLimit\n this._eventBuilders = []\n\n this._phoneCodeHash = {}\n this.session = session\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId)\n this.apiHash = apiHash\n\n this._requestRetries = args.requestRetries\n this._connectionRetries = args.connectionRetries\n this._retryDelay = args.retryDelay || 0\n if (args.proxy) {\n this._log.warn('proxies are not supported')\n }\n this._proxy = args.proxy\n this._timeout = args.timeout\n this._autoReconnect = args.autoReconnect\n\n this._connection = args.connection\n // TODO add proxy support\n\n this._floodWaitedRequests = {}\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: null, // no proxies yet.\n }),\n })\n }\n\n this._args = args\n // These will be set later\n this._config = null\n this.phoneCodeHashes = []\n this._borrowedSenderPromises = {}\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\n\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession()\n\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n })\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log\n )\n\n await this._sender.connect(connection)\n\n this.session.setAuthKey(this._sender.authKey)\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ))\n\n this._updateLoop()\n }\n\n async _initSession() {\n await this.session.load()\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6 ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80)\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000)\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)\n })), 1500)\n }, 3, 100)\n } catch (err) {\n await this.disconnect()\n this.connect()\n\n return\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState())\n } catch (e) {\n\n }\n }\n }\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect()\n }\n\n await Promise.all(\n Object.values(this._borrowedSenderPromises).map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect()\n }\n })\n })\n )\n\n this._borrowedSenderPromises = {}\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect()\n this.session.delete()\n this._eventBuilders = []\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`)\n const DC = utils.getDC(newDc)\n this.session.setDC(newDc, DC.ipAddress, DC.port)\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(null)\n this.session.setAuthKey(null)\n await this.disconnect()\n return this.connect()\n }\n\n async _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId)\n }\n\n // endregion\n // export region\n\n _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId]\n }\n\n async _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId]\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId)\n this._borrowedSenderPromises[dcId] = senderPromise\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId]\n }\n });\n }\n return senderPromise\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId)\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\n logger: this._log,\n dcId: dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupBorrowedSender.bind(this),\n })\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ))\n if (this.session.dcId !== dcId) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`)\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId: dcId }))\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n },\n ))\n await sender.send(req)\n }\n sender.dcId = dcId\n return sender\n } catch (e) {\n await sender.disconnect()\n }\n }\n return null\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n async downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args)\n }\n\n async downloadMedia(messageOrMedia, args) {\n let date\n let media\n if (messageOrMedia instanceof constructors.Message) {\n date = messageOrMedia.date\n media = messageOrMedia.media\n } else {\n date = new Date().getTime()\n media = messageOrMedia\n }\n if (typeof media == 'string') {\n throw new Error('not implemented')\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args)\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args)\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args)\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args)\n }\n }\n\n async downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697]\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm'\n let photo\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return null\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n )\n }\n photo = entity.photo\n }\n\n let dcId\n let loc\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId\n const size = isBig ? photo.photoBig : photo.photoSmall\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n localId: size.localId,\n volumeId: size.volumeId,\n big: isBig,\n })\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return null\n }\n try {\n return this.downloadFile(loc, {\n dcId: dcId,\n })\n } catch (e) {\n // TODO this should never raise\n throw e;\n /*if (e.message === 'LOCATION_INVALID') {\n const ie = await this.getInputEntity(entity)\n if (ie instanceof constructors.InputPeerChannel) {\n const full = await this.invoke(new requests.channels.GetFullChannel({\n channel: ie,\n }))\n return this._downloadPhoto(full.fullChat.chatPhoto, { sizeType })\n } else {\n return null\n }\n } else {\n throw e\n }*/\n }\n }\n\n async downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumb || !stickerSet.thumb.location) {\n return undefined\n }\n\n const { location } = stickerSet.thumb\n\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash\n }),\n localId: location.localId,\n volumeId: location.volumeId,\n }),\n { dcId: stickerSet.thumbDcId }\n )\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return null\n }\n const indexOfSize = sizeTypes.indexOf(sizeType)\n let size\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i])\n if (size) {\n return size\n }\n }\n return null\n }\n\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes)\n } else {\n data = size.bytes\n }\n return data\n }\n\n async _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo\n }\n if (!(photo instanceof constructors.Photo)) {\n return\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType)\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size)\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n )\n }\n\n async _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document\n }\n if (!(doc instanceof constructors.Document)) {\n return\n }\n\n let size = null\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : null\n if (!size && doc.mimeType.startsWith('video/')) {\n return\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size)\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n )\n }\n\n _downloadContact(media, args) {\n throw new Error('not implemented')\n }\n\n _downloadWebDocument(media, args) {\n throw new Error('not implemented')\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests')\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime()\n let attempt = 0\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request)\n const result = await promise\n //this.session.processEntities(result)\n // this._entityCache.add(result)\n return result\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL' ||\n e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`)\n await sleep(2000)\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`)\n await sleep(e.seconds * 1000)\n } else {\n throw e\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError ||\n e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`)\n const shouldRaise = e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n if (shouldRaise && await checkAuthorization(this)) {\n throw e\n }\n await this._switchDC(e.newDc)\n } else {\n throw e\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`)\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0]\n } catch (e) {\n }\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect()\n }\n\n if (await checkAuthorization(this)) {\n return\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash\n }\n\n await authFlow(this, apiCredentials, authParams)\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams)\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback])\n }\n\n _handleUpdate(update) {\n //this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = []\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x)\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities)\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, null)\n } else {\n this._processUpdate(update, null)\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || []\n const args = {\n update: update,\n others: others,\n }\n this._dispatchUpdate(args)\n }\n\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /*CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n /*CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: null,\n others: null,\n channelId: null,\n ptsDate: null,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update)\n if (event) {\n await callback(event)\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true\n }\n }\n return false\n }\n}\n\nasync function timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms).then(() => Promise.reject(new Error('TIMEOUT'))),\n ])\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n return await cb()\n } catch (err) {\n if (i === times - 1) {\n throw err\n }\n\n await Helpers.sleep(pause)\n }\n }\n}\n\nmodule.exports = TelegramClient\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\n","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","const BigInt = require('big-integer')\nconst { readBigIntFromBuffer, readBufferFromBigInt, getByteArray, sha1, generateRandomBytes, modExp } = require('../Helpers')\n\nconst PUBLIC_KEYS = [{\n 'fingerprint': [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n 'n': BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n 'e': 65537\n}, {\n 'fingerprint': [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n 'n': BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n 'e': 65537\n}, {\n 'fingerprint': [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n 'n': BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n 'e': 65537\n}, {\n 'fingerprint': [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n 'n': BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n 'e': 65537\n}]\n\nconst _serverKeys = {}\n\nPUBLIC_KEYS.forEach(({ fingerprint, ...keyInfo }) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = keyInfo\n})\n\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint]\n if (!key) {\n return undefined\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length)\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand])\n\n // rsa module rsa.encrypt adds 11 bits for padding which we don't want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n const payload = readBigIntFromBuffer(toEncrypt, false)\n const encrypted = modExp(payload, BigInt(key.e), key.n)\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false)\n}\n\nmodule.exports = {\n encrypt,\n}\n","class RequestState {\n constructor(request, after = null) {\n this.containerId = null\n this.msgId = null\n this.request = request\n this.data = request.getBytes()\n this.after = after\n this.result = null\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve\n this.reject = reject\n })\n }\n}\n\nmodule.exports = RequestState\n","const { Connection } = require('./Connection')\nconst { ConnectionTCPFull } = require('./TCPFull')\nconst { ConnectionTCPAbridged } = require('./TCPAbridged')\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated')\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n}\n","const crypto = require('./crypto')\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error('Key and iv need to be a buffer')\n }\n\n this.cipher = crypto.createCipheriv('AES-256-CTR', key, iv)\n }\n\n encrypt(data) {\n return Buffer.from(this.cipher.update(data))\n }\n}\n\nmodule.exports = CTR\n","import { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer, expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number,\n apiHash: string,\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n while (1) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n while (1) {\n if (isScanningComplete){\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n}> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","import { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\n\nexport interface progressCallback {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst REQUEST_TIMEOUT = 15000;\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let { partSizeKb, fileSize, workers = 1, end } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - offset % ONE_MB;\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n await foreman.releaseWorker();\n break;\n }\n\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\n ]);\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n\nclass Foreman {\n private deferred: Deferred | undefined;\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && (this.activeWorkers <= this.maxWorkers)) {\n this.deferred.resolve();\n }\n }\n}\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\n}\n","import { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\n\ninterface OnProgress {\n // Float between 0 and 1.\n (progress: number): void;\n\n isCanceled?: boolean;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst UPLOAD_TIMEOUT = 15 * 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n let sendingParts = [];\n let end = i + workers;\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n sendingParts.push((async () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\n );\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partCount);\n onProgress(progress);\n }\n })());\n\n }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: '', // This is not a \"flag\", so not sure if we can make it optional.\n });\n}\n\nfunction generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), false);\n}\n\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","import TelegramClient from './TelegramClient';\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password: password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n while (1) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2'\n","const NewMessage = require('./NewMessage')\nconst Raw = require('./Raw')\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = { NewMessage, StopPropagation, Raw }\n","const { EventBuilder } = require('./common')\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: null,\n func: null,\n }) {\n super()\n if (!args.types) {\n this.types = true\n } else {\n this.types = args.types\n }\n }\n\n build(update, others = null) {\n return update\n }\n}\n\nmodule.exports = Raw\n","class EventBuilder {\n constructor(args = {\n chats: null, blacklistChats: null, func: null,\n },\n ) {\n this.chats = args.chats\n this.blacklistChats = Boolean(args.blacklistChats)\n this.resolved = false\n this.func = args.func\n }\n\n build(update, others = null) {\n\n }\n}\n\nclass EventCommon {\n\n}\n\n\nmodule.exports = { EventBuilder, EventCommon }\n","const Memory = require('./Memory')\nconst StringSession = require('./StringSession')\nconst CacheApiSession = require('./CacheApiSession')\nconst LocalStorageSession = require('./LocalStorageSession')\nconst IdbSession = require('./IdbSession')\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n}\n","const MemorySession = require('./Memory')\nconst AuthKey = require('../crypto/AuthKey')\nconst BinaryReader = require('../extensions/BinaryReader')\nconst CURRENT_VERSION = '1'\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = null) {\n super()\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string')\n }\n session = session.slice(1)\n const r = StringSession.decode(session)\n const reader = new BinaryReader(r)\n this._dcId = reader.read(1)\n .readUInt8(0)\n const serverAddressLen = reader.read(2)\n .readInt16BE(0)\n this._serverAddress = String(reader.read(serverAddressLen))\n this._port = reader.read(2)\n .readInt16BE(0)\n this._key = reader.read(-1)\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64')\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64')\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey()\n await this._authKey.setKey(this._key)\n }\n }\n\n save() {\n if (!this.authKey) {\n return ''\n }\n const dcBuffer = Buffer.from([this.dcId])\n const addressBuffer = Buffer.from(this.serverAddress)\n const addressLengthBuffer = Buffer.alloc(2)\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0)\n const portBuffer = Buffer.alloc(2)\n portBuffer.writeInt16BE(this.port, 0)\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]))\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined\n }\n\n return this.authKey\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined\n }\n\n this.authKey = authKey\n }\n}\n\nmodule.exports = StringSession\n","const StorageSession = require('./StorageSession')\n\nconst CACHE_NAME = 'GramJs'\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey)\n const cache = await self.caches.open(CACHE_NAME)\n return cache.delete(request)\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey)\n const cache = await self.caches.open(CACHE_NAME)\n const cached = await cache.match(request)\n return cached ? cached.text() : null\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey)\n const response = new Response(data)\n const cache = await self.caches.open(CACHE_NAME)\n return cache.put(request, response)\n }\n}\n\nmodule.exports = CacheApiSession\n","const StorageSession = require('./StorageSession')\n\nclass LocalStorageSession extends StorageSession {\n async _delete() {\n return localStorage.removeItem(this._storageKey)\n }\n\n async _fetchFromCache(key) {\n return localStorage.getItem(this._storageKey)\n }\n\n async _saveToCache(key, data) {\n return localStorage.setItem(this._storageKey, data)\n }\n}\n\nmodule.exports = LocalStorageSession\n","const StorageSession = require('./StorageSession')\nconst idb = require('idb-keyval')\n\nconst CACHE_NAME = 'GramJs'\n\nclass IdbSession extends StorageSession {\n async _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`)\n }\n\n async _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`)\n }\n\n async _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data)\n }\n}\n\nmodule.exports = IdbSession\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumb) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: result.hash,\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n hash: result.hash,\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function loadNotificationsSettings() {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n isShowPreviews,\n}: {\n isSilent: boolean;\n isShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: isShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : undefined,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({ langPack, langCode }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: IInputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nfunction updateLocalDb(result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import { ApiOnProgress, ApiUpdate, OnApiUpdate } from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionId = '') {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(sessionId, handleUpdate);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index 9ccd312a..ca49716b 100644 --- a/dist/index.html +++ b/dist/index.html @@ -1 +1 @@ -Telegram
\ No newline at end of file +Telegram
\ No newline at end of file diff --git a/dist/main.c7769ee2bb8655152f13.js b/dist/main.c83b96912904b35c9d32.js similarity index 99% rename from dist/main.c7769ee2bb8655152f13.js rename to dist/main.c83b96912904b35c9d32.js index 85c4f98e..7ea24c4b 100644 --- a/dist/main.c7769ee2bb8655152f13.js +++ b/dist/main.c83b96912904b35c9d32.js @@ -1,2 +1,2 @@ -!function(e){function t(t){for(var n,r,o=t[0],c=t[1],d=0,a=[];d=0&&I(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),O[n].renderTimes.push(t),O[n].renderCount++}}catch(t){Object(d.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const o=w(u);return e.$element=y(e,[o]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(d.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){return m(e)?M(e.children[0]):e.target}function A(e,t){m(e)?A(e.children[0],t):e.target=t}function k(e){const{cursor:t,byCursor:n}=f.hooks.state;var r;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(r=f,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,r.scheduleNextState&&r.forceUpdate||(r.scheduleNextState=Object(u.h)(()=>function(e){e.isMounted&&e.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue})}(r)),r.forceUpdate=Object(u.i)(()=>function(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}(r))),r.scheduleNextState(),r.forceUpdate())})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function T(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,o=f,c=()=>{if(!o.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(d.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(c):e(c),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return T(u.b,e,t)}function N(e,t){return T(u.d,e,t)}function D(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function L(e,t){return D(()=>e,t)}function F(e){return D(()=>({current:e}),[])}function B(e,t=c.a){return function(n){const r=F(n),u=F();return(!u.current||r.current&&!t(r.current,n))&&(r.current=n,u.current=g(e,n)),u.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(o.k)(Object.values(O),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"db",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return o})),n.d(t,"o",(function(){return c})),n.d(t,"q",(function(){return d})),n.d(t,"E",(function(){return a})),n.d(t,"p",(function(){return i})),n.d(t,"C",(function(){return s})),n.d(t,"z",(function(){return f})),n.d(t,"A",(function(){return l})),n.d(t,"y",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"M",(function(){return p})),n.d(t,"N",(function(){return g})),n.d(t,"O",(function(){return y})),n.d(t,"l",(function(){return v})),n.d(t,"F",(function(){return I})),n.d(t,"X",(function(){return O})),n.d(t,"T",(function(){return j})),n.d(t,"U",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"j",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"mb",(function(){return k})),n.d(t,"W",(function(){return T})),n.d(t,"x",(function(){return P})),n.d(t,"Q",(function(){return N})),n.d(t,"P",(function(){return D})),n.d(t,"eb",(function(){return L})),n.d(t,"Bb",(function(){return F})),n.d(t,"a",(function(){return B})),n.d(t,"e",(function(){return R})),n.d(t,"d",(function(){return x})),n.d(t,"r",(function(){return U})),n.d(t,"t",(function(){return _})),n.d(t,"u",(function(){return G})),n.d(t,"v",(function(){return $})),n.d(t,"jb",(function(){return W})),n.d(t,"ib",(function(){return z})),n.d(t,"Z",(function(){return H})),n.d(t,"Y",(function(){return K})),n.d(t,"cb",(function(){return V})),n.d(t,"bb",(function(){return q})),n.d(t,"ab",(function(){return Y})),n.d(t,"I",(function(){return J})),n.d(t,"c",(function(){return Q})),n.d(t,"tb",(function(){return Z})),n.d(t,"ub",(function(){return X})),n.d(t,"ob",(function(){return ee})),n.d(t,"pb",(function(){return te})),n.d(t,"wb",(function(){return ne})),n.d(t,"sb",(function(){return re})),n.d(t,"xb",(function(){return ue})),n.d(t,"yb",(function(){return oe})),n.d(t,"vb",(function(){return ce})),n.d(t,"zb",(function(){return de})),n.d(t,"qb",(function(){return ae})),n.d(t,"rb",(function(){return ie})),n.d(t,"R",(function(){return se})),n.d(t,"S",(function(){return fe})),n.d(t,"nb",(function(){return le})),n.d(t,"H",(function(){return be})),n.d(t,"k",(function(){return he})),n.d(t,"fb",(function(){return me})),n.d(t,"hb",(function(){return pe})),n.d(t,"gb",(function(){return ge})),n.d(t,"lb",(function(){return ye})),n.d(t,"b",(function(){return ve})),n.d(t,"g",(function(){return Ie})),n.d(t,"K",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"kb",(function(){return je})),n.d(t,"G",(function(){return Ce})),n.d(t,"Ab",(function(){return Ee})),n.d(t,"w",(function(){return Se})),n.d(t,"m",(function(){return Me})),n.d(t,"n",(function(){return Ae})),n.d(t,"s",(function(){return ke}));const r="Telegram",u=" [Inactive]",o="Telegram WebZ alpha a684b4f",c=!1,d=!1,a=!1,i="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",s="GramJs:sessionId",f=!1,l="tt-global-state",b=30,h=5e3,m=!1,p="tt-media",g="tt-media-avatars",y="tt-media-progressive",v="tt-custom-bg",I="tt-lang-packs",w=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),O=1,j=750,C=w?60:40,E=2*C,S=72,M=w?30:25,A=100,k=42,T=42,P=20,N=30,D=200,L=500,F=25,B=!1,R=2,x=R,U=16,_=1e4,G="editable-message-text",$="editable-message-text-modal",W=1440,z=1150,H=1275,K=925,V=600,q=950,Y=450,J=1e9,Q=100,Z=13,X=11,ee=160,te=120,ne=64,re=48,ue=32,oe=64,ce=64,de=160,ae=140,ie=80,se="MEMOJI_STICKER",fe=200,le=450,be=450,he="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",me="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",pe=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ge=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ye=777e3,ve=0,Ie=1,we=10,Oe=5,je=2147483646,Ce=["android","ios"],Ee="TelegramTips",Se="https://bugs.telegram.org/?tag_ids=41&sort=time",Me="#0F0F0F",Ae="#0a0a0a8c",ke="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return y})),n.d(t,"e",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"b",(function(){return w})),n.d(t,"a",(function(){return O})),n.d(t,"f",(function(){return j})),n.d(t,"h",(function(){return C}));var r=n(0),u=n(1),o=n(31),c=n(22),d=n(9),a=n(26),i=n(3),s=n(21);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;const g=Object(d.i)((function(){h.forEach(e=>e(l))}));function y(e){"object"==typeof e&&e!==l&&(l=e,g())}function v(){return l}function I(){return m}function w(e,t){b[e]||(b[e]=[],m[e]=t=>{!function(e,t){b[e]&&b[e].forEach(e=>{const n=e(l,m,t);n&&y(n)})}(e,t)}),b[e].push(t)}function O(e){h.push(e)}function j(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function C(e=(()=>({})),t=(()=>({}))){return n=>function(u){const[d]=Object(r.r)(Object(c.a)(p)),i=Object(o.a)();Object(r.n)(()=>()=>{p.delete(d)},[d]);let b=p.get(d);if(b||(b={mapStateToProps:e,mapReducersToProps:t,ownProps:u,areMappedPropsChanged:!1,forceUpdate:i,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(d,b)),b.areMappedPropsChanged&&(b.areMappedPropsChanged=!1),!b.mappedProps||!Object(a.a)(b.ownProps,u)){b.ownProps=u;try{b.mappedProps={...e(l,u),...t(y,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},b.mappedProps,u))}}function E(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?["LENGTH"]:n.filter(n=>e[n]!==t[n])}u.o&&(window.getGlobal=v,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function o(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function c(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function d(e,t){const n=new Set(t.map(String));return o(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,o]=Array.isArray(n)?n:[n,n],[c,d]=t;let a,i;if("function"==typeof c?(a=c(e)||0,i=c(r)||0):"string"==typeof c&&(a=e[c]||0,i=r[c]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof d?(t=d(e)||0,n=d(r)||0):"string"==typeof d&&(t=e[d]||0,n=r[d]||0),"asc"===o?t-n:n-t}}let u,o;return"function"==typeof t?(u=t(e)||0,o=t(r)||0):"string"==typeof t&&(u=e[t]||0,o=r[t]||0),"asc"===n?u-o:o-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return o})),n.d(t,"m",(function(){return c})),n.d(t,"j",(function(){return d})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";var r=n(59);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(60);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var o=n(61);n.d(t,"ApiMessageEntityTypes",(function(){return o.a})),n.d(t,"MAIN_THREAD_ID",(function(){return o.b})),n.d(t,"MESSAGE_DELETED",(function(){return o.c}));var c=n(62);n.o(c,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return c.ApiMediaFormat}));var d=n(63);n.d(t,"ApiMediaFormat",(function(){return d.a}));n(64),n(65)},function(e,t,n){"use strict";n.d(t,"X",(function(){return r.b})),n.d(t,"Y",(function(){return r.c})),n.d(t,"Z",(function(){return r.d})),n.d(t,"wb",(function(){return r.g})),n.d(t,"ob",(function(){return r.e})),n.d(t,"vb",(function(){return r.f})),n.d(t,"Cb",(function(){return r.h})),n.d(t,"W",(function(){return r.a})),n.d(t,"kb",(function(){return u.w})),n.d(t,"jb",(function(){return u.v})),n.d(t,"hb",(function(){return u.t})),n.d(t,"mb",(function(){return u.y})),n.d(t,"ib",(function(){return u.u})),n.d(t,"nb",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"T",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"lb",(function(){return u.x})),n.d(t,"fb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"xb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"J",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"gb",(function(){return u.s})),n.d(t,"d",(function(){return u.b})),n.d(t,"Ab",(function(){return u.C})),n.d(t,"zb",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"eb",(function(){return u.q})),n.d(t,"I",(function(){return u.n})),n.d(t,"Bb",(function(){return u.D})),n.d(t,"A",(function(){return i})),n.d(t,"yb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"M",(function(){return l})),n.d(t,"N",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"K",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"sb",(function(){return g})),n.d(t,"tb",(function(){return y})),n.d(t,"pb",(function(){return v})),n.d(t,"cb",(function(){return I})),n.d(t,"ub",(function(){return w})),n.d(t,"db",(function(){return O})),n.d(t,"U",(function(){return j})),n.d(t,"V",(function(){return C})),n.d(t,"rb",(function(){return E})),n.d(t,"qb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"bb",(function(){return T})),n.d(t,"G",(function(){return P})),n.d(t,"O",(function(){return N})),n.d(t,"t",(function(){return D})),n.d(t,"u",(function(){return L})),n.d(t,"L",(function(){return F})),n.d(t,"y",(function(){return B})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return x})),n.d(t,"P",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"E",(function(){return G})),n.d(t,"D",(function(){return $})),n.d(t,"C",(function(){return z})),n.d(t,"B",(function(){return H})),n.d(t,"b",(function(){return V})),n.d(t,"i",(function(){return q})),n.d(t,"R",(function(){return Y})),n.d(t,"S",(function(){return J})),n.d(t,"ab",(function(){return Q})),n.d(t,"s",(function(){return Z})),n.d(t,"w",(function(){return X})),n.d(t,"r",(function(){return ee})),n.d(t,"a",(function(){return te}));var r=n(23),u=n(24),o=n(4),c=n(1),d=n(58);const a=new RegExp(c.fb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t=!1){const{text:n,photo:r,video:u,audio:o,voice:c,document:d,sticker:a,contact:i,poll:s,invoice:f}=e.content;if(e.groupedId)return n?`${t?"":"🖼 "}${n.text}`:"Album";if(r)return n?`${t?"":"🖼 "}${n.text}`:"Photo";if(u)return u.isGif?n?`${t?"":"GIF "}${n.text}`:"GIF":n?`${t?"":"📹 "}${n.text}`:"Video";if(a)return"Sticker "+a.emoji;if(o){const e=[o.title,o.performer].filter(Boolean).join(" — ")||n&&n.text;return e?"🎧 "+e:"Audio"}return c?n?`${t?"":"🎤 "}${n.text}`:"Voice Message":d?`${t?"":"📎 "}${n?n.text:d.fileName}`:i?"Contact":s?"📊 "+s.summary.question:f?"Invoice":n?n.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:o,voice:c,document:d,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||o||c||d||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:o,voice:c,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||o||c||a||i||s||f)&&(Object(d.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===o.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===o.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function I(e){return!!e.content.action}function w(e){return e.chatId===c.lb&&E(e)}function O(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e){return e.id>0?Object(r.c)(e):Object(u.i)(e)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=c.I}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(53);function k(e){return e.content}function T(e){return Boolean(P(e)||N(e)||B(e)||F(e)||function(e){return e.content.contact}(e)||R(e)||D(e)||L(e)||function(e){return e.content.voice}(e))}function P(e){return e.content.photo}function N(e){return e.content.video}function D(e){return e.content.action}function L(e){return e.content.audio}function F(e){return e.content.sticker}function B(e){return e.content.document}function R(e){return e.content.poll}function x(e){return e.content.invoice}function U(e){return e.content.webPage}function _(e){const t=U(e);return t?t.photo:void 0}function G(e){const t=function(e){const t=P(e)||N(e)||B(e)||F(e)||_(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function $(e,t){const{photo:n,video:r,sticker:u,audio:o,voice:c,document:d}=e.content,a=_(e);if(!(n||r||u||a||o||c||d))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(K(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(K(e))return;return V(r)?W(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return W(r,s);case"download":return s+"?download"}if(d)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(d)||K(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(o)switch(t){case"micro":case"pictogram":return;default:return W(o,s)}if(c)switch(t){case"micro":case"pictogram":return;default:return s}}function W(e,t){return M.h&&M.i?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function z(e,t){const{sticker:n,video:r,audio:u,voice:c}=e.content;return n&&"inline"===t&&n.isAnimated?o.ApiMediaFormat.Lottie:r&&M.h&&("viewerFull"===t||"inline"===t&&V(r))?o.ApiMediaFormat.Progressive:u||c?c&&!M.g?o.ApiMediaFormat.BlobUrl:o.ApiMediaFormat.Progressive:o.ApiMediaFormat.BlobUrl}function H(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function K(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function V(e){return e.isGif||e.isRound||e.size<=10485760}function q(e,t,n=!1){const r=X(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||J(e)}function J(e){return e.sizes.find(e=>"x"===e.type)||e.sizes.find(e=>"m"===e.type)||e.sizes.find(e=>"s"===e.type)||e.thumbnail}function Q(e){if(e.width&&e.height)return e}function Z(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function X(e,t,n){let r;switch(n){case"media":r=e=>{const t=N(e);return P(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=B;break;case"links":r=e=>U(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=L;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function ee(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function te(e,t){return`${e}_${t}`}n(54)},function(e,t,n){"use strict";n.d(t,"S",(function(){return Pe})),n.d(t,"kb",(function(){return Ne})),n.d(t,"V",(function(){return De})),n.d(t,"Db",(function(){return a})),n.d(t,"f",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"O",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"xb",(function(){return b})),n.d(t,"n",(function(){return h})),n.d(t,"g",(function(){return m})),n.d(t,"K",(function(){return p})),n.d(t,"d",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"j",(function(){return v})),n.d(t,"i",(function(){return I})),n.d(t,"M",(function(){return w})),n.d(t,"h",(function(){return O})),n.d(t,"q",(function(){return j})),n.d(t,"y",(function(){return T})),n.d(t,"r",(function(){return P})),n.d(t,"m",(function(){return N})),n.d(t,"nb",(function(){return D})),n.d(t,"X",(function(){return F})),n.d(t,"db",(function(){return B})),n.d(t,"x",(function(){return R})),n.d(t,"Eb",(function(){return x})),n.d(t,"gb",(function(){return U})),n.d(t,"lb",(function(){return _})),n.d(t,"ob",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"C",(function(){return W})),n.d(t,"E",(function(){return z})),n.d(t,"B",(function(){return H})),n.d(t,"bb",(function(){return K})),n.d(t,"zb",(function(){return V})),n.d(t,"F",(function(){return q})),n.d(t,"Ab",(function(){return Y})),n.d(t,"Bb",(function(){return J})),n.d(t,"yb",(function(){return Q})),n.d(t,"a",(function(){return Z})),n.d(t,"W",(function(){return X})),n.d(t,"k",(function(){return ee})),n.d(t,"mb",(function(){return te})),n.d(t,"D",(function(){return ne})),n.d(t,"l",(function(){return re})),n.d(t,"H",(function(){return ue})),n.d(t,"T",(function(){return oe})),n.d(t,"cb",(function(){return ce})),n.d(t,"qb",(function(){return de})),n.d(t,"J",(function(){return ae})),n.d(t,"b",(function(){return ie})),n.d(t,"e",(function(){return se})),n.d(t,"Cb",(function(){return fe})),n.d(t,"ib",(function(){return le})),n.d(t,"G",(function(){return be})),n.d(t,"Q",(function(){return he})),n.d(t,"p",(function(){return me})),n.d(t,"R",(function(){return pe})),n.d(t,"U",(function(){return ge})),n.d(t,"I",(function(){return ye})),n.d(t,"Z",(function(){return ve})),n.d(t,"P",(function(){return Ie})),n.d(t,"pb",(function(){return we})),n.d(t,"ab",(function(){return Oe})),n.d(t,"rb",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"tb",(function(){return Ee})),n.d(t,"t",(function(){return Le})),n.d(t,"A",(function(){return Se})),n.d(t,"w",(function(){return Me})),n.d(t,"v",(function(){return Ae})),n.d(t,"Y",(function(){return ke})),n.d(t,"u",(function(){return Te})),n.d(t,"z",(function(){return E})),n.d(t,"s",(function(){return S})),n.d(t,"ub",(function(){return M})),n.d(t,"vb",(function(){return A})),n.d(t,"c",(function(){return k})),n.d(t,"eb",(function(){return Fe})),n.d(t,"fb",(function(){return Be})),n.d(t,"hb",(function(){return Re})),n.d(t,"wb",(function(){return xe}));var r=n(19),u=n(7),o=n(4),c=n(1),d=n(5);function a(e,t){return e.users.byId[t]}function i(e,t){return e.chats.byId[t]}function s(e,t){const n=Object(d.T)(t);return!!n&&a(e,n)}function f(e,t){return t===e.currentUserId}function l(e,t){const n=s(e,t);return n&&Object(d.vb)(n)}function b(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function h(e,t){if(!Object(d.kb)(t.id)&&!Object(d.ib)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==c.P?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(d.wb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function m(e,t){const n=i(e,t),r=n&&Object(d.T)(n),u=r&&a(e,r);if(u&&Object(d.vb)(u))return u}function p(e,t){const n=i(e,t),r=m(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(d.qb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:c}=u.threadsById[o.MAIN_THREAD_ID]||{};return c&&!c.length}function g(e){return Boolean(e.chats.listIds.active)}function y(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some(e=>e&&e.includes(t))}function v(e,t){const n=i(e,t);if(n&&y(e,t))return n.folderId===c.g?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function w(e,t,n=c.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===c.b)return!!r&&r.includes(t);if(n===c.g)return!!u&&u.includes(t);const{byId:o}=e.chatFolders,{pinnedChatIds:d}=o[n]||{};return!!d&&d.includes(t)}function O(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function j(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((e,t)=>{const r=n[t];return r&&r.unreadCount&&!r.isMuted?e+r.unreadCount:e},0)}var C=n(3);function E(e){return e.stickers.search}function S(e){return e.gifs.search}function M(e,t){return e.stickers.setsById[t]}function A(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function k(e,t){const{animatedEmojis:n}=e;if(n&&n.stickers)return t=t.replace("️",""),n.stickers.find(e=>e.emoji===t)}function T(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function P(e){const{chatId:t}=T(e)||{};return t?i(e,t):void 0}function N(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function D(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function L(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const o=u.threadsById[n];return o?o[r]:void 0}function F(e,t,n){return L(e,t,n,"listedIds")}function B(e,t,n){return L(e,t,n,"outlyingIds")}function R(e,t,n,r){switch(r){case"thread":return x(e,t,n);case"pinned":return U(e,t);case"scheduled":return _(e,t)}}function x(e,t,n){return L(e,t,n,"viewportIds")}function U(e,t){return L(e,t,o.MAIN_THREAD_ID,"pinnedIds")}function _(e,t){return L(e,t,o.MAIN_THREAD_ID,"scheduledIds")}function G(e,t,n){return L(e,t,n,"scrollOffset")}function $(e,t,n){return L(e,t,n,"replyingToId")}function W(e,t,n){return L(e,t,n,"editingId")}function z(e,t){return L(e,t,o.MAIN_THREAD_ID,"editingScheduledId")}function H(e,t,n){return L(e,t,n,"draft")}function K(e,t,n){return L(e,t,n,"noWebPage")}function V(e,t,n){return L(e,t,n,"threadInfo")}function q(e,t,n){return L(e,t,n,"firstMessageId")}function Y(e,t,n){if(n===o.MAIN_THREAD_ID)return i(e,t);const r=V(e,t,n);return r?i(e,r.originChannelId||t):void 0}function J(e,t,n){if(n===o.MAIN_THREAD_ID)return;const r=V(e,t,n);return r?r.topMessageId:void 0}function Q(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:o}=n;return u||o?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||o&&o===e.threadInfo.topMessageId)):void 0}function Z(e,t,n){const r=T(e);if(!r)return!1;const{threadInfo:u}=Q(e,t,n)||{};return t===r.chatId&&(r.threadId===o.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function X(e,t,n){const r=x(e,t,n);if(!r||!r.length)return!0;let u;if(n===o.MAIN_THREAD_ID){const n=i(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=V(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=c.I&&!ee(e,t,u)||r[r.length-1]>=u}function ee(e,t,n){const r=N(e,t);return r?r[n]:void 0}function te(e,t,n){const r=D(e,t);return r?r[n]:void 0}function ne(e,t,n,r){if("scheduled"===r){const n=z(e,t);return n?te(e,t,n):void 0}{const r=W(e,t,n);return r?ee(e,t,r):void 0}}function re(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find(e=>e.content.poll&&e.content.poll.id===t),n)break}return n}function ue(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function oe(e,t){const n=ue(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ce(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=i(e,t.chatId)||{};return Object(d.rb)(t)||!n||n0?a(e,n):i(e,n)}function ae(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?i(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function ie(e,t,n){const r=i(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(d.kb)(r.id),o=f(e,t.chatId),c=Object(d.hb)(r),a=Object(d.mb)(r),s=Object(d.ib)(r),l=Object(d.ub)(t),b=Object(d.sb)(t),h=Object(d.cb)(t),{content:m}=t,p=(o||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(d.pb)(t)&&!t.viaBotId,g=Object(d.e)(r,n)&&!l,y=u||r.isCreator||!s&&!Object(d.xb)(r,"pinMessages")||Object(d.q)(r,"pinMessages");let v=!h&&y,I=!1;const w=U(e,r.id);v&&(I=Boolean(w&&w.includes(t.id)),v=!I);const O=u||b||c||r.isCreator||Object(d.q)(r,"deleteMessages"),j=O&&!l&&(u&&!o||c&&(b||Object(d.q)(r,"deleteMessages"))),C=!h&&p&&(b||s&&(r.isCreator||Object(d.q)(r,"editMessages"))),E=!h&&!l,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,P=!h&&(s||a),N=!h;return{noOptions:[g,C,v,I,O,j,E,A,k,T,P,N].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:I,canDelete:O,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:P,canSelect:N}}function se(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=T(e)||{},u=n&&N(e,n);if(!u||!t||!r)return{};const o=t.map(t=>u[t]&&ie(e,u[t],r)).filter(Boolean);return{canDelete:o.every(e=>e.canDelete),canDeleteForAll:o.every(e=>e.canDeleteForAll)}}function fe(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function le(e,t,n){if(n===o.MAIN_THREAD_ID){const n=i(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(d.rb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=V(e,t,n);if(!r)return;return r.lastReadInboxMessageId?r.lastMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId):r.lastReadInboxMessageId:r.topMessageId}}function be(e,t,n){if(n===o.MAIN_THREAD_ID){if(!i(e,t))return}else{const r=V(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const r=B(e,t,n),u=F(e,t,n),c=N(e,t);if(!c||!r&&!u)return;const d=le(e,t,n);if(r){const e=r.find(e=>!d||e>d&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled));if(e)return e}if(u){const e=u.find(e=>!d||e>d&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled));if(e)return e}}function he(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function me(e,t){const n=Object.values(e.chats.byId).find(e=>Object(d.nb)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=i(e,Number(n));return u&&Object(d.nb)(u)&&r[u.id].byId[t]}))}function pe(e){const{selectedMessages:t}=e;return Boolean(t)}function ge(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function ye(e,t,n){const r=N(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function ve(e,t,n){const r=N(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function Ie(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=ve(e,t,n);return u&&u.every(e=>r.includes(e))}function we(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Oe(e,t){const n=i(e,t);if(!n)return;if(!l(e,n))return;const r=N(e,t),u=x(e,t,o.MAIN_THREAD_ID);if(!r||!u)return;const c=Object(C.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),d=Object(C.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return c&&d&&d>c?void 0:c?r[c]:void 0}function je(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:o,shouldAutoDownloadMediaInGroups:c,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(o&&Object(d.kb)(n.id)||c&&Object(d.jb)(n)||a&&Object(d.ib)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Ce(e,t){const n=Object(d.O)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,o=n.isGif||n.isRound;return r&&!o||u&&o}function Ee(e){return e.settings.byKey.shouldLoopStickers}function Se(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;const r=Object(d.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Me(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=T(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ae(e){const t=Me(e);if(t)return e.localMediaSearch.byChatId[t]}function ke(e,t){return e.management.byChatId[t]}function Te(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;if(Object(d.kb)(t))return"user";const r=i(e,t);return r?Object(d.jb)(r)?"group":"channel":void 0}function Pe(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Ne(e){const{users:t,isChatInfoShown:n}=e,o=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),c=Boolean(!u.f&&Se(e)),d=function(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==E(e).query,i=void 0!==S(e).query,{chatId:s}=T(e)||{},f=t.selectedId,l=g(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return o?r.l.PollResults:c?r.l.Search:d?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function De(e){return void 0!==Ne(e)}function Le(e){return e.globalSearch.query}function Fe(e){return e.payment.messageId}function Be(e){return e.payment.formId}function Re(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function xe(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"n",(function(){return u})),n.d(t,"e",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"b",(function(){return d})),n.d(t,"i",(function(){return a})),n.d(t,"k",(function(){return i})),n.d(t,"f",(function(){return s})),n.d(t,"l",(function(){return f})),n.d(t,"c",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"h",(function(){return h})),n.d(t,"g",(function(){return m})),n.d(t,"a",(function(){return p})),n.d(t,"m",(function(){return g})),n.d(t,"o",(function(){return v}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),o="Mac OS"===u,c="iOS"===u,d="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.cb||window.innerWidth<=r.bb&&window.innerHeight<=r.ab,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(o||c)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=window.devicePixelRatio||1,g=c;let y;function v(){return Boolean(y)}new Promise(e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n}).then(e=>{y=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...o)=>{u?(clearTimeout(u),u=void 0):n&&e(...o),u=self.setTimeout(()=>{r&&e(...o),u=void 0},t)}}function u(e,t,n=!0){let r,u,o;return(...c)=>{u=!0,o=c,r||(n&&(u=!1,e(...o)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...o)},t))}}function o(e){return a(h,e)}function c(e){return a(m,e)}function d(e){return a(i,e)}function a(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function i(e){Promise.resolve().then(e)}function s(e){self.requestIdleCallback?self.requestIdleCallback(e):i(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return o})),n.d(t,"h",(function(){return c})),n.d(t,"j",(function(){return d})),n.d(t,"d",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"b",(function(){return h}));const f=e=>new Promise(t=>{setTimeout(()=>t(),e)});function l(){return new Promise(e=>{requestAnimationFrame(e)})}let b;function h(e,t=!1){b?t?b.unshift(e):b.push(e):(b=[e],requestAnimationFrame(()=>{const e=b;b=void 0,e.forEach(e=>e())}))}function m(e){return h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(70),u=n.n(r),o=n(1),c=n(22);let d;const a=new Map,i=new Map;function s(e,t=""){return d||(o.o&&console.log(">>> START LOAD WORKER"),d=new u.a,function(e){d.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(d)return b({type:"callMethod",name:e,args:t});o.o&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&d.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(c.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),d.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return y})),n.d(t,"c",(function(){return O})),n.d(t,"b",(function(){return j}));var r=n(1),u=n(13),o=n(10);var c=n(3),d=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(44);const b={en:d,es:a,it:i,pl:s,ru:f},h=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],m={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},p=new Map;let g;const{addCallback:y,removeCallback:v,runCallbacks:I}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let w;async function O(e,t){if(g&&e===w)return document.documentElement.lang=e,void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(o.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(n){if(b[e])try{const t=await fetch(b[e]),r=await t.json(),u=Object(c.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.o&&console.error(e)}p.clear(),w=e,g=n,document.documentElement.lang=e,t&&t(),I(g)}}function j(e,t,n){if(void 0!==t){const r=p.get(`${e}_${t}_${n}`);if(r)return r}if(!g)return e;const r=g[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=w&&m[w]?m[w](e):0;return h[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return p.set(`${e}_${t}_${n}`,r),r}return u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const o={},c={};async function d(e,t){if(!o[e]){switch(e){case u.Auth:o[u.Auth]=n.e(4).then(n.bind(null,93));break;case u.Main:r.o&&console.log(">>> START LOAD MAIN BUNDLE"),o[u.Main]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,91));break;case u.Extra:o[u.Extra]=Promise.all([n.e(0),n.e(2)]).then(n.bind(null,92))}o[e].then(f)}const d=await o[e];return c[e]||(c[e]=d),a(e,t)}function a(e,t){const n=c[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"b",(function(){return d}));const r=self.caches;let u;async function o(e,t,n){if(r)try{const o=new Request(t),c=await r.open(e),d=await c.match(o);if(!d)return;switch(n){case u.Text:return await d.text();case u.Blob:{const e=await d.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=d.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await d.json();default:return}}catch(e){return void console.warn(e)}}async function c(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),o=new Request(t),c=new Response(u),d=await r.open(e);return await d.put(o,c)}catch(e){return void console.warn(e)}}async function d(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return d})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function o(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const o=new Uint8Array(u);for(;u--;)o[u]=r.charCodeAt(u);return new Blob([o],{type:n})}function c(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)})}function d(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)})])}async function f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function o(e){return e.indexOf(u)<0?e.replace(r,""):e}t.a=/(?:\u2624|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},function(e,t,n){"use strict";var r=n(0),u=n(20);n(82);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(12),o=n(31);t.a=(e,t,n=!1,c=!1)=>{const d=Object(u.c)(e,t),a=Object(o.a)();return c&&Object(u.b)(a),Object(r.n)(()=>{n||d||Object(u.d)(e,t).then(a)},[e,a,d,t,n]),d}},function(e,t,n){"use strict";n.d(t,"d",(function(){return c})),n.d(t,"e",(function(){return d})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var o="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function c(e){return o.find(t=>t.id===e)}function d(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=o.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,o,c)=>{const d=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${d}${u}`),o&&(a+=`${d}${o}`),c&&(a+=`${d}${c}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=d(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";let r,u,o,c,d,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return d})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(o||(o={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(c||(c={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(d||(d={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(78);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",d),window.addEventListener("unhandledrejection",d);const o=Date.now();let c=!1;function d(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!c){if(Date.now()-o<=5e3){if(localStorage.getItem(r.A))localStorage.removeItem(r.A);else{if(!localStorage.getItem(r.C))return;localStorage.removeItem(r.C)}return c=!0,void window.location.reload()}0}}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(30),o=n(3);const c=[1,8,5,2,7,4,6];function d(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(e.id===r.lb)return t("ServiceNotifications").toLowerCase();if(e.type&&"userTypeBot"===e.type)return"bot";if(!e.status)return"";switch(e.status.type){case"userStatusEmpty":return t("ALongTimeAgo");case"userStatusLastMonth":return t("WithinAMonth");case"userStatusLastWeek":return t("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=e.status;if(!n)return t("LastSeen.Offline");const r=new Date,o=new Date(1e3*n);if(o>=r)return t("LastSeen.JustNow");const c=new Date(r.getTime()-o.getTime());if(c.getTime()/1e3<60)return t("LastSeen.JustNow");if(c.getTime()/1e3<3600){return t("LastSeen.MinutesAgo",Math.floor(c.getTime()/1e3/60))}const d=new Date;if(d.setHours(0,0,0,0),o>d){if(c.getTime()/1e3<21600){return t("LastSeen.HoursAgo",Math.floor(c.getTime()/1e3/60/60))}return t("LastSeen.TodayAt",Object(u.h)(o))}const a=new Date;return a.setDate(r.getDate()-1),d.setHours(0,0,0,0),o>a?t("LastSeen.YesterdayAt",Object(u.h)(o)):t("LastSeen.AtDate",Object(u.b)(o))}case"userStatusOnline":return t("Online");case"userStatusRecently":return t("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.lb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.lb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(o.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return c[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return a})),n.d(t,"v",(function(){return i})),n.d(t,"t",(function(){return s})),n.d(t,"y",(function(){return f})),n.d(t,"u",(function(){return l})),n.d(t,"z",(function(){return b})),n.d(t,"j",(function(){return h})),n.d(t,"p",(function(){return m})),n.d(t,"i",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"f",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"x",(function(){return I})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return j})),n.d(t,"c",(function(){return C})),n.d(t,"a",(function(){return E})),n.d(t,"o",(function(){return S})),n.d(t,"h",(function(){return M})),n.d(t,"g",(function(){return A})),n.d(t,"s",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return P})),n.d(t,"B",(function(){return N})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return L})),n.d(t,"q",(function(){return F})),n.d(t,"n",(function(){return B})),n.d(t,"D",(function(){return R}));var r=n(4),u=n(1),o=n(3),c=n(23),d=n(11);function a(e){return e>0}function i(e){return s(e)||f(e)}function s(e){return"chatTypeBasicGroup"===e.type}function f(e){return"chatTypeSuperGroup"===e.type}function l(e){return"chatTypeChannel"===e.type}function b(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function h(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function m(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function p(e,t,n=!1){return n||t&&e.id===t.id&&t.isSelf?Object(d.b)("SavedMessages"):e.title||Object(d.b)("HiddenName")}function g(e){if(e.fullInfo)return e.fullInfo.about}function y(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function v(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function I(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function j(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function C(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!a(e.id)||(l(e)?O(e,"postMessages"):w(e)||!j(e,"sendMessages"))))}function E(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!j(e,"sendMedia"),canAttachPolls:(n||!j(e,"sendPolls"))&&(!a(e.id)||t),canSendStickers:n||!j(e,"sendStickers"),canSendGifs:n||!j(e,"sendGifs"),canAttachEmbedLinks:n||!j(e,"embedLinks")}}function S(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function M(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function A(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function k(e){return e.folderId===u.g}function T(e){return s(e)||(f(e)||l(e))&&e.isCreator}function P(e,t,n,r){const u=n.excludedChatIds?new Set(n.excludedChatIds):void 0,o=n.excludedChatIds?new Set(n.includedChatIds):void 0,c=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(r||Object.keys(e).map(Number)).filter(r=>function(e,t,n,r,u,o){if(r&&r.has(e.id))return!1;if(u&&u.has(e.id))return!0;if(o&&o.has(e.id))return!0;if(k(e)&&t.excludeArchived)return!1;if(e.isMuted&&t.excludeMuted)return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(a(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(i(e))return!!t.groups;if(l(e))return!!t.channels}return!1}(e[r],n,t,u,o,c)),n.pinnedChatIds]}function N(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(k(e))return!1;break;case"archived":if(!k(e))return!1}return!e.isRestricted&&!e.isNotJoined}const c=t.map(t=>e[t]).filter(u),d=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>d.has(e.id)):[],otherChats:Object(o.k)(n?c.filter(e=>!n.includes(e.id)):c,A,"desc")}}function D(e,t,n,r){const[u]=P(e,t,n,r),o=u.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:o.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:o.some(e=>e.unreadMentionsCount||!e.isMuted&&(e.unreadCount||e.hasUnreadMark))}}function L(e,t,n,r,u){const{id:o,title:c,emoticon:d,description:a,pinnedChatIds:i,excludedChatIds:s,includedChatIds:f,excludeArchived:l,excludeMuted:b,excludeRead:h,...m}=n;if(Object.values(m).filter(Boolean).length>1||s&&s.length||f&&f.length){return u("Chats",function(e,t,n,r){const[u,o]=P(e,t,n,r),{pinnedChats:c,otherChats:d}=N(e,u,o,"folder");return c.length+d.length}(e,t,n,r))}return m.bots?u("FilterBots"):m.groups?u("FilterGroups"):m.channels?u("FilterChannels"):m.contacts?u("FilterContacts"):m.nonContacts?u("FilterNonContacts"):void 0}function F(e){return!!e&&e.id<0}function B(e,t){if(t&&!a(e))return t.isSelf?"You":Object(c.b)(t)}function R(e,t,n=!1,r){return Object(o.k)(e,e=>{const u=t[e];if(!u)return 0;let o=0;return u.lastMessage&&(o+=u.lastMessage.date),n&&u.isVerified&&(o+=3e9),r&&r.includes(e)&&(o+=Date.now()+(r.length-r.indexOf(e))),o},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),o=n(20),c=n(35);n(80);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:d,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:I,ariaLabel:w,href:O,download:j,disabled:C,ripple:E,faded:S,tabIndex:M})=>{let A=Object(r.q)(null);e&&(A=e);const[k,T]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",I&&"loading",E&&"has-ripple",S&&"faded",k&&"clicked"),N=Object(r.m)(e=>{!C&&n&&n(e),T(!0),setTimeout(()=>{T(!1)},400)},[C,n]),D=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return O?r.a.createElement("a",{ref:A,className:P,href:O,title:w,download:j,tabIndex:M},l,!C&&E&&r.a.createElement(c.a,null)):r.a.createElement("button",{ref:A,type:t,className:P,onClick:N,onContextMenu:d,onMouseDown:D,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":w,title:w,tabIndex:M},I?r.a.createElement("div",null,r.a.createElement("span",null,"Please wait.."),r.a.createElement(o.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(c.a,null))}},function(e,t,n){"use strict";function r(e,t){const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[n]===t[n])}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),o={},c=new Map,d={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){d[e]||(d[e]=0,document.addEventListener(e,h));(function(e){o[e]||(o[e]=new Map);return o[e]})(e).set(t,n),function(e){const t=c.get(e);if(t)return t;const n=new Set;return c.set(e,n),n}(t).add(e),d[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){d[e]--,d[e]||document.removeEventListener(e,h),o[e].delete(t),c.get(t).delete(e)}function b(e){const t=c.get(e);t&&(t.forEach(t=>l(t,e)),c.delete(e))}function h(e){const t=o[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},o=()=>{e.preventDefault()},c=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?o:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(c),n))return;r=r.parentNode}}}r.o&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:o,delegatedEventsByElement:c,documentEventCounters:d})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,o="fast",c=!1)=>{const[d,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(!1);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),d||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},c?0:350)));const l=s||e&&n,b=Boolean(i.current),h=e||b;return{shouldRender:h,transitionClassNames:Object(u.a)(o&&"opacity-transition",o,l&&"open",h&&"shown",b&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return d})),n.d(t,"k",(function(){return a})),n.d(t,"n",(function(){return i})),n.d(t,"h",(function(){return f})),n.d(t,"g",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"c",(function(){return m})),n.d(t,"d",(function(){return g})),n.d(t,"e",(function(){return y})),n.d(t,"i",(function(){return v})),n.d(t,"a",(function(){return I})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return j}));var r=n(11);const u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],o=["January","February","March","April","May","June","July","August","September","October","November","December"],c=o.map(e=>e.toLowerCase());function d(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function a(e){return d(e).getTime()}function i(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function s(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function f(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function l(e){const t="number"==typeof e?new Date(e):e,n=d(new Date);if(t>=n)return f(t);const o=new Date(n);if(o.setDate(n.getDate()-7),t>=o)return Object(r.b)("Weekday.Short"+u[t.getDay()]);const c=t.getFullYear()!==n.getFullYear();return p(t,Object(r.b)(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM"))}function b(e){return p("number"==typeof e?new Date(e):e,Object(r.b)("formatterYearMax")||"dd.MM.yyyy")}function h(e,t=!1){return p(e,Object(r.b)(t?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy")}function m(e,t=!1,n=!1){const o="number"==typeof e?new Date(e):e,c=d(new Date);if(!n){if(s(o)===s(c))return(t?C:E)(Object(r.b)("Weekday.Today"));const e=new Date(c);if(e.setDate(c.getDate()-1),s(o)===s(e))return(t?C:E)(Object(r.b)("Weekday.Yesterday"));const n=new Date(c),d=new Date(c);if(n.setDate(c.getDate()-7),d.setDate(c.getDate()+7),o>=n&&o<=d){const e=u[o.getDay()];return t?C(Object(r.b)("Weekday.Short"+e)):E(Object(r.b)("Weekday."+e))}}const a=o.getFullYear()!==c.getFullYear(),i=t?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate";return(t?C:E)(p(o,Object(r.b)(i)||"d MMMM yyyy"))}function p(e,t){const n=e.getDate(),u=e.getMonth();return t.replace("LLLL",Object(r.b)(o[u])).replace("MMMM",Object(r.b)("Month.Gen"+o[u])).replace("MMM",Object(r.b)("Month.Short"+o[u])).replace("MM",String(u+1).padStart(2,"0")).replace("dd",String(n).padStart(2,"0")).replace("d",String(n)).replace("yyyy",String(e.getFullYear()))}function g(e){const t="number"==typeof e?new Date(e):e;return`${m(t,!0)}, ${f(t)}`}function y(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function v(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const u=(e=Math.floor(e/60))%60;e-=u;const o=(e=Math.floor(e/60))%60;return o>0&&t.push(String(o).padStart(2,"0")),t.push(String(u).padStart(o>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function I(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],d=(t?u[1]:u[0]).toLowerCase(),a=c.findIndex(e=>e.startsWith(d));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function j(e){return e+86400}function C(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function E(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"a",(function(){return l}));var r=n(10),u=n(1),o=n(2),c=n(7);function d(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function a(){return!!c.j&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(u.o&&console.log("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(u.o&&console.log("[PUSH] Push messaging isn't supported."),!1):(u.o&&console.log("[PUSH] Push notifications aren't supported."),!1))}async function i(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=d(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){u.o&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function s(){if(!a())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await i(t)}async function f(){if(!a())return;const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(d(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await i(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=d(t);u.o&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?u.o&&console.log("[PUSH] Permission for Notifications was denied"):u.o&&console.log("[PUSH] Unable to subscribe to push.",e)}}}function l(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#21212140"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";var r=n(0),u=n(8);n(85);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:d,download:a,disabled:i,destructive:s,ariaLabel:f}=e,l=Object(r.m)(e=>{if(i||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[i,c]),b=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return i||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[i,c]),h=Object(u.a)("MenuItem",n,i&&"disabled",s&&"destructive"),m=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t}),o);return d?r.a.createElement("a",{tabIndex:0,className:h,href:d,download:a,"aria-label":f,title:f,target:"_blank",rel:"noopener noreferrer"},m):r.a.createElement("div",{role:"button",tabIndex:0,className:h,onClick:l,onKeyDown:b,"aria-label":f,title:f},m)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(79);t.a=()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),o=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,o=u.getBoundingClientRect(),c=u.offsetWidth/2;t([...e,{x:r.clientX-o.x-c/2,y:r.clientY-o.y-c/2,size:c}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:o},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(73),u=n.n(r),o=n(7),c=n(14),d=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(d.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(o.o)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(c.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(c.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),o=n(1),c=n(7),d=n(67),a=n(8),i=n(68),s=n(51);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return o=e,c=n.highlight,o.reduce((e,t)=>{if("string"!=typeof t||!c)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(c.toLowerCase()),o=n[u+c.length];if(u<0||o&&o.match(f))return[...e,t];const d=[];return d.push(t.substring(0,u)),d.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+c.length))),d.push(t.substring(u+c.length)),[...e,...d]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let o=n.shift(),c=0;for(;o;){const e=t.indexOf(o,c);u.push(t.substring(c,e)),o.startsWith("@")?u.push(r.a.createElement(i.a,{username:o},o)):u.push(r.a.createElement(s.a,{text:o,url:o})),c=e+o.length,o=n.shift()}return u.push(t.substring(c)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var o,c;return e},[e])}function h(e,t,n){return c.c?e:e.reduce((e,o)=>{if("string"!=typeof o)return[...e,o];const c=o.split(u.a),i=o.match(u.a)||[];return e.push(c[0]),i.reduce((e,o,i)=>{const s=Object(d.a)(Object(u.b)(o)),f=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(r.a.createElement("img",{className:f,src:`./img-apple-${"big"===t?"160":"64"}/${s}.png`,alt:o})),"html"===n&&e.push(`${o}`);const l=2*i+2;return c[l]&&e.push(c[l]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,o)=>{const c=n.trimLeft(),d=n.length-c.length;return e.push(String.fromCharCode(160).repeat(d)+c),u!==o.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(o.fb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),o=n.match(l)||[];return e.push(u[0]),o.reduce((e,n,o)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const c=2*o+2;return u[c]&&e.push(u[c]),e},e)},[])}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"q",(function(){return o})),n.d(t,"G",(function(){return c})),n.d(t,"r",(function(){return d})),n.d(t,"F",(function(){return a})),n.d(t,"K",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"I",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"L",(function(){return m})),n.d(t,"v",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return I})),n.d(t,"J",(function(){return w})),n.d(t,"cb",(function(){return O})),n.d(t,"i",(function(){return j})),n.d(t,"j",(function(){return C})),n.d(t,"T",(function(){return E})),n.d(t,"bb",(function(){return S})),n.d(t,"f",(function(){return A})),n.d(t,"x",(function(){return k})),n.d(t,"ib",(function(){return T})),n.d(t,"jb",(function(){return P})),n.d(t,"t",(function(){return N})),n.d(t,"N",(function(){return D})),n.d(t,"M",(function(){return L})),n.d(t,"l",(function(){return F})),n.d(t,"E",(function(){return B})),n.d(t,"m",(function(){return R})),n.d(t,"gb",(function(){return x})),n.d(t,"fb",(function(){return U})),n.d(t,"O",(function(){return _})),n.d(t,"p",(function(){return G})),n.d(t,"hb",(function(){return $})),n.d(t,"n",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"lb",(function(){return K})),n.d(t,"mb",(function(){return V})),n.d(t,"e",(function(){return q})),n.d(t,"db",(function(){return Y})),n.d(t,"k",(function(){return J})),n.d(t,"P",(function(){return Z})),n.d(t,"Q",(function(){return X})),n.d(t,"S",(function(){return ee})),n.d(t,"R",(function(){return te})),n.d(t,"W",(function(){return ue})),n.d(t,"s",(function(){return oe})),n.d(t,"X",(function(){return ce})),n.d(t,"V",(function(){return ae})),n.d(t,"U",(function(){return ie})),n.d(t,"Z",(function(){return fe})),n.d(t,"Y",(function(){return le})),n.d(t,"u",(function(){return be})),n.d(t,"ab",(function(){return he})),n.d(t,"a",(function(){return me})),n.d(t,"o",(function(){return pe})),n.d(t,"kb",(function(){return ge})),n.d(t,"eb",(function(){return ye})),n.d(t,"C",(function(){return ve})),n.d(t,"A",(function(){return Ie})),n.d(t,"y",(function(){return we})),n.d(t,"D",(function(){return Oe})),n.d(t,"z",(function(){return je})),n.d(t,"B",(function(){return Ce})),n.d(t,"g",(function(){return Ee})),n.d(t,"h",(function(){return Se}));var r=n(1),u=n(3);function o(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function c(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:o(e,t,[...r||[],...u])}function d(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:o}=e.chats,c=o[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...c.photos||[]]}};return i.id&&i.type?d(e,{...o,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.g?"archived":"active";let o=e.chats.listIds;return Object.keys(o).forEach(e=>{const n=o[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(o={...o,[e]:n.filter(e=>e!==t)}):o={...o,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:o}},t,{folderId:n||void 0})}function l(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}var b=n(4),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(e,t){const n=t.reduce((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e),{});return Object.keys(n).map(Number).forEach(t=>{e=I(e,t,n[t])}),e}function I(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function w(e,t,n,r){const u=Object(h.m)(e,t)||{},o={...u[n],...r};return o.id?p(e,t,{...u,[n]:o}):e}function O(e,t,n,r){const u=Object(h.nb)(e,t)||{},o={...u[n],...r};return o.id?N(e,t,{...u,[n]:o},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const o=Object(u.j)(r,n),c=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.X)(e,t,r),o=Object(h.db)(e,t,r),c=Object(h.Eb)(e,t,r),d=Object(h.gb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",o),e=y(e,t,r,"viewportIds",c),e=y(e,t,r,"pinnedIds",d)}),c.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;c.forEach(n=>{const{fromChatId:o,fromMessageId:c}=n.forwardInfo,d=Object(h.k)(e,o,c);r&&u===c&&(e=m(e,t)),d&&(e=w(e,o,c,{threadInfo:void 0}))})}return e=p(e,t,o)}function C(e,t,n){const r=Object(h.nb)(e,t);if(!r)return e;const o=Object(u.j)(r,n);let c=Object(h.lb)(e,t);return c&&(n.forEach(e=>{c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",c)),e=N(e,t,o,void 0)}function E(e,t,n,r){const u=Object(h.X)(e,t,n),o=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!o.length?e:y(e,t,n,"listedIds",M([...u||[],...o]))}function S(e,t,n,r){const u=Object(h.db)(e,t,n),o=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!o.length?e:y(e,t,n,"outlyingIds",M([...u||[],...o]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const o=Object(h.Eb)(e,t,n)||[];if(o.includes(u))return e;return y(e,t,n,"viewportIds",M([...o.length{e=T(e,t.chatId,t.threadId,t)}),e}function N(e,t,n,r){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function L(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function F(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,o,c,d,a=!1){const{selectedMessages:i}=e;c&&(d=Object(h.Z)(e,t,c));const s=d||[o];if(!i)return F(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const c=Object(h.x)(e,t,n,r),d=c.indexOf(f[f.length-1]),a=c.indexOf(o),i=Math.min(d,a),s=Math.max(d,a),b=c.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:R(e)}function R(e){return{...e,selectedMessages:void 0}}function x(e,t,n,r,o){const c=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(c,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let o;if(t||!u)o=n;else{const e=new Set(u.map(e=>e.id));o=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:o}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const o=[...Object(h.vb)(e,t),...n||[]],c=Object(u.o)(o.map(({id:e})=>e)),d=Object(u.c)(o,"id"),a=c.map(e=>d[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var z=n(45);function H(e,t){return{...e,users:{...e.users,byId:t}}}function K(e,t,n){const{byId:r}=e.users,{hash:o,userIds:c}=e.contactList||{},d=r[t],a=n.isMin&&d&&!d.isMin,i={...d,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&c&&!c.includes(t)&&(e={...e,contactList:{hash:o||0,userIds:[t,...c]}}),H(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=K(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=K(e,r,t[r]))}),e}function Y(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function J(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],H(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):z.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,o){const{resultsByType:c}=e.globalSearch||{},d=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=c&&c[r]?c[r].foundIds:void 0;if(void 0!==a&&Object.keys(d).every(e=>a.includes(Q(d[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(5);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],isActive:r,query:u})}function oe(e,t,n,r,u,o){const c=Object(ne.a)(t,n);return re(e,c,{...e.localTextSearch.byChatThreadKey[c],results:{foundIds:r,totalCount:u,nextOffsetId:o}})}function ce(e,t,n,r,o,c){const d=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[d]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return oe(e,t,n,Object(u.a)(i,s)?i:s,o,c)}function de(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return de(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,o,c){const{resultsByType:d}=e.localMediaSearch.byChatId[t]||{},a=d&&d[n]?d[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,o){return de(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:o}}})}(e,t,n,Object(u.a)(a,i)?a:i,o,c)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function me(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function pe(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ge(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function ye(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function ve(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function we(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:o}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:o}}}}function Oe(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function je(e,t){return{...e,payment:{...e.payment,...t}}}function Ce(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:o,title:c}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:o,title:c}}}}function Ee(e){return{...e,payment:{}}}function Se(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:d,success:a,disabled:i,readOnly:s,placeholder:f,autoComplete:l,inputMode:b,maxLength:h,onChange:m,onInput:p,onKeyPress:g,onKeyDown:y,onBlur:v})=>{const I=d||a||c,w=Object(u.a)("input-group",o&&"touched",d?"error":a&&"success",i&&"disabled",s&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:w},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,value:o||"",placeholder:f,maxLength:h,autoComplete:l,inputMode:b,disabled:i,readOnly:s,onChange:m,onInput:p,onKeyPress:g,onKeyDown:y,onBlur:v}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),o=n(20);n(81);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:d,checked:a,disabled:i,round:s,blocking:f,isLoading:l,onChange:b,onCheck:h})=>{const m=Object(r.m)(e=>{b&&b(e),h&&h(e.currentTarget.checked)},[b,h]),p=Object(u.a)("Checkbox",i&&"disabled",s&&"round",l&&"loading",f&&"blocking");return r.a.createElement("label",{className:p},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:a,disabled:i,onChange:m}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label"},c),d&&r.a.createElement("span",{className:"subLabel"},d)),l&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(50);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c}));var r=n(0);let u,o=!1;const c=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),o=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{o=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(o&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function o(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function c(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return c}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(29),o=n(69),c=n(52),d=n(42),a=n(8),i=n(43);n(83);t.a=({ref:e,containerRef:t,isOpen:n,className:s,style:f,children:l,positionX:b="left",positionY:h="top",autoClose:m=!1,footer:p,noCloseOnBackdrop:g=!1,onCloseAnimationEnd:y,onClose:v,onMouseEnter:I,onMouseLeave:w})=>{let O=Object(r.q)(null);e&&(O=e);const j=t||O,{transitionClassNames:C}=Object(u.a)(n,y);Object(r.n)(()=>n&&v?Object(d.a)(v):void 0,[n,v]),Object(c.a)(([e])=>{void 0!==e&&Object(i.b)(200)},[n]);const E=((e,t,n)=>{const[u,o]=Object(r.r)(-1);Object(r.n)(()=>{o(-1)},[t]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n();if(38!==t.keyCode&&40!==t.keyCode)return;const c=document.activeElement,d=Array.from(r.children);let a=c&&d.indexOf(c)||u;if(38===t.keyCode&&a>0)a--;else if(40===t.keyCode&&a{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(36);const m={[r.ApiMediaFormat.DataUri]:c.a.Text,[r.ApiMediaFormat.BlobUrl]:c.a.Blob,[r.ApiMediaFormat.Lottie]:c.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.h?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.L){const n=e.startsWith("avatar")?u.N:u.M,r=await c.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.g||(t=await b(t)),"image/webp"===r.type&&!Object(a.o)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=w(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let c=!1;return r.addEventListener("sourceopen",()=>{if(c)return;c=!0;const u=r.addSourceBuffer("audio/mpeg");Object(o.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(o.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.g){const e=await Object(d.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=w(t),f=e.type}if("image/webp"===f&&!Object(a.o)()){const t=await Object(d.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=w(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.o&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function I(e){Object(o.b)(e)}function w(e){return e instanceof Blob?URL.createObjectURL(e):e}a.h&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const c=await Object(o.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!c)return;const{arrayBuffer:d,mimeType:a,fullSize:i}=c;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:d,mimeType:a,fullSize:i}},[d])})},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(9);let u=o();function o(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}const c=Object(r.g)(()=>{u=o()},250,!0);window.addEventListener("resize",c),window.addEventListener("orientationchange",c),t.a={get:()=>u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onTab:[]};function o(e){return c()||document.addEventListener("keydown",d,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),c()||document.removeEventListener("keydown",d,!1)}(e)}}function c(){return Object.values(u).some(e=>Boolean(e.length))}function d(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";var r=n(0),u=n(2);const o=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function c(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function d(e,t){const n=[],r=[],u=e.length;let d,a,i,s,f,l,b,h,m,p,g,y,v;for(d=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(I=e.charCodeAt(b++))-48<10?I-22:I-65<26?I-65:I-97<26?I-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=c(i-h,a,0===h),Math.floor(i/a)>2147483647-d)throw RangeError("punycode_overflow(3)");d+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,d),i++}var I;if(t)for(i=0,v=n.length;iObject(s.l)(t,["openTelegramLink"]))(({url:e,text:t,className:n,children:u,openTelegramLink:o})=>{const c=Object(r.m)(t=>!(!(t.ctrlKey||t.altKey||t.shiftKey||t.metaKey)&&e&&(e.match(i.hb)||e.match(i.gb)))||(t.preventDefault(),o({url:e}),!1),[o,e]);if(!e)return;const d=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:d,onClick:c},u||t)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return o})),n.d(t,"a",(function(){return c})),n.d(t,"c",(function(){return d}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(e){const{fileName:t,mimeType:n}=e;return o(t,n)}function o(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function c(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function d(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return c}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:o,fieldError:c,description:d}=u?r[u]:r[n];return{field:o,fieldError:c,description:d||t}}const o={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function c(e){return Object.values(e).reduce((e,t)=>{const n=o[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return c}));var r=n(9);let u;function o(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&o(e,t)})}function c(e){Object(r.b)(()=>{e()&&c(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(47);n(84);t.a=({trigger:e,className:t,children:n,positionX:o="left",positionY:c="top",footer:d})=>{const a=Object(r.q)(null),i=Object(r.q)(null),[s,f]=Object(r.r)(!1);return r.a.createElement("div",{ref:i,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=a.current;if(!s||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{f(!s)},isOpen:s}),r.a.createElement(u.a,{ref:a,containerRef:i,isOpen:s,className:t||"",positionX:o,positionY:c,footer:d,autoClose:!0,onClose:()=>{f(!1)}},n))}},function(e,t,n){"use strict";var r=n(0),u=n(22),o=n(1),c=n(27);const d=new Set(["key","ref","teactFastList","teactOrderKey"]),a={autoPlay:"autoplay",autoComplete:"autocomplete"},i={};function s(e,t,n,u,c,{skipComponentUpdate:d=!1,forceIndex:a=!1,fragment:i,moveDirection:g}={}){if(!d&&t&&n&&Object(r.d)(t)&&Object(r.d)(n)&&!Object(r.c)(t,n)&&(n=function(e,t){return e.componentInstance.props=t.componentInstance.props,Object(r.j)(e.componentInstance)}(t,n)),!d&&n&&Object(r.d)(n)&&n.componentInstance.isMounted&&l(n,u,c,e),t===n)return n;if(!t&&n){Object(r.d)(n)&&(n=f(n,u,c,e));const t=b(n);Object(r.k)(n,t),a&&e.childNodes[c]?e.insertBefore(t,e.childNodes[c]):(i||e).appendChild(t)}else if(t&&!n)e.removeChild(Object(r.b)(t)),Object(r.l)(t);else if(t&&n)if(Object(r.c)(t,n)){Object(r.d)(n)&&(n=f(n,u,c,e));const o=b(n);Object(r.k)(n,o),e.replaceChild(o,Object(r.b)(t)),Object(r.l)(t)}else{const u=Object(r.d)(t)&&Object(r.d)(n);if(u||Object(r.k)(n,Object(r.b)(t)),Object(r.f)(t)&&Object(r.f)(n)){if(g){const n=Object(r.b)(t),u=e.childNodes["up"===g?c:c+1];u?e.insertBefore(n,u):(i||e).appendChild(n)}u||function(e,t,n){const r=Object.keys(e.props),u=Object.keys(t.props);r.forEach(r=>{void 0!==e.props[r]&&void 0===t.props[r]&&p(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?m(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(p(e,t,n),m(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return o.o&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let c=0;const d=e.children.reduce((e,r,o)=>{let d="props"in r?r.props.key:void 0;if(d&&!u.has(d))return s(n,r,void 0,t,-1),e;if(!d){const u=t.children[o],c=u&&"props"in u?u.props.key:void 0;if(!u||c)return s(n,r,void 0,t,-1),e;d="__indexKey#"+o}return e[d]={$element:r,index:c++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,f=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,o=d[u];if(!o)return a||(a=[],i=r),void a.push(e);a&&(f=f.concat(h(a,i,n,t)),i=void 0,a=void 0);const c="props"in e?e.props.teactOrderKey:void 0,b=o.index!==l&&o.order!==c,m=b&&l>o.index;b&&!m||l++,f.push(s(n,o.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:m?"down":"up"}}))}),a&&(f=f.concat(h(a,i,n,t)));return f}(e,t,n);const u=Math.max(e.children.length,t.children.length),c=[],d=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:d}:void 0);u&&c.push(u)}d&&n.appendChild(d);return c}(t,n,u?e:Object(r.b)(t))}}return n}function f(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:o}=e;if(!o.isMounted){l(e=Object(r.i)(o),t,n,u);const c=e.children[0];Object(r.d)(c)&&(e.children=[f(c,e,0,u)]),o.isMounted=!0}return e}function l(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=s(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function b(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return b(e.children[0]);const{tag:t,props:n,children:u=[]}=e,o=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=o),Object.keys(n).forEach(e=>{m(o,e,n[e])}),e.children=u.map((t,n)=>s(o,void 0,t,e,n)),o}function h(e,t,n,r){if(1===e.length)return[s(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),o=e.map(e=>s(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),o}throw new Error("Unexpected input")}function m(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(c.a)(e,t,n):t.startsWith("data-")?e.setAttribute(t,n):d.has(t)||(e[a[t]||t]=n))}function p(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(c.c)(e,t,n):t.startsWith("data-")?e.removeAttribute(t):d.has(t)||delete e[a[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(i),i[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=i[n];r.children=[s(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";var r=n(15);const u=new RegExp(`^(?:${r.a.source})+$`,"");t.a=e=>{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return o})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,o="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(55),u=n(33);let o=!1;const c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,d=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=c.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const o=Math.round(d(u[e].r,u[t].r,n)),c=Math.round(d(u[e].g,u[t].g,n)),a=Math.round(d(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(d(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${o},${c},${a},${i/255})`:`rgb(${o},${c},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=o&&t,c=n?0:1,d=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),o&&document.documentElement.classList.add("disable-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("disable-animations")},500),o=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(c,d,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(c,d)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function o(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map(e=>e.toString(16).padStart(4,"0")).join("-")}return t}function c(e){const t={categories:[],emojis:{}};for(let n=0;n({userOrChat:t?Object(c.Db)(e,t):void 0}),(e,t)=>Object(o.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:o})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&o({username:e.substring(1)})},className:"text-entity-link"},n))},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0cfac43ee01937a2bf09.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),o=n(11),c=n(66);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:d}=e.settings.byKey;Object(o.c)(d),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.k?"is-touch-env":"is-pointer-env"),Object(c.a)(t,n>0),u.i&&document.body.classList.add("is-safari"),u.d?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0}))},function(e,t,n){"use strict";var r=n(2),u=n(1),o=n(10),c=n(32),d=n(13);Object(r.b)("initApi",(e,t)=>{const n=localStorage.getItem(u.C)||void 0;return Object(o.c)(t.apiUpdate,n),{...e,authIsSessionRemembered:Boolean(n)}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(o.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(o.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(o.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(o.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(o.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(o.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(o.a)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{const{sessionId:r}=n;localStorage.setItem(u.C,r)}),Object(r.b)("signOut",()=>{(async()=>{await Object(c.c)(),await Object(o.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{localStorage.removeItem(u.C),d.b(u.M),d.b(u.N),d.b(u.O),d.b(u.l),d.b(u.F),Object(r.d)().init()}),Object(r.b)("disconnect",()=>{(async()=>{await Object(o.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(o.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t,n){"use strict";var r=n(2),u=n(1),o=n(32),c=n(39),d=n(11);Object(r.b)("apiUpdate",(e,t,n)=>{switch(u.o&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(o.b)(),Object(d.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":{if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()});const{sessionId:u}=e;u&&t.authRememberMe&&Object(r.d)().saveSession({sessionId:u});break}}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(c.lb)(Object(r.e)(),t.id,t),currentUserId:t.id})}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(21),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),o=n(2),c=n(7);function d(e){const t=e.data;if(u.o&&console.log("[SW] New action from service worker",t),!t.type)return;const n=Object(o.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}c.j&&window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.o&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.o&&console.log("[SW] ServiceWorker ready"),navigator.serviceWorker.addEventListener("message",d)):(u.o&&console.error("[SW] ServiceWorker not available"),Object(o.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.o&&console.error("[SW] ServiceWorker registration failed: ",e)}});var a=n(57);const i={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{}},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.r,isBackgroundBlurred:!0,patternColor:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},privacy:{}},twoFaSettings:{}};var s=n(4),f=n(9),l=n(3),b=n(6);const h=Object(f.g)((function(){Object(f.c)(()=>{if(!m)return;const e=Object(o.e)();if(e.isLoggingOut)return;const t={...i,...Object(l.l)(e,["authState","authPhoneNumber","authRememberMe","authIsSessionRemembered","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","push"]),isChatInfoShown:g(e),users:y(e),chats:v(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:w(e)},n=JSON.stringify(t);localStorage.setItem(u.A,n)})}),1e3,!1);let m=!1;function p(e){if(!u.z){if(localStorage.getItem(u.C))return m=!0,Object(o.a)(h),function(e){u.o&&console.time("global-state-cache-read");const t=localStorage.getItem(u.A),n=t?JSON.parse(t):void 0;u.o&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey});return{...e,...n}}(e);m=!1}}function g(e){return window.innerWidth>u.Z&&e.isChatInfoShown}function y(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.y).filter(e=>e>0),...Object.keys(t)].slice(0,u.B);return{byId:Object(l.l)(t,r),selectedId:window.innerWidth>u.Z?n:void 0}}function v(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.y)],{chatId:n}=Object(b.y)(e)||{};return{...e.chats,byId:Object(l.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(b.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.y),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[s.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(l.l)(r.byId,u.viewportIds),threadsById:{[s.MAIN_THREAD_ID]:u}})});const r=Object(b.y)(e);return{byChatId:t,messageLists:!r||c.f?void 0:[{...r,threadId:s.MAIN_THREAD_ID,type:"thread"}]}}function w(e){const{byKey:t}=e.settings;return{byKey:t,privacy:{}}}u.z||(Object(o.b)("saveSession",()=>{m=!0,Object(o.a)(h)}),Object(o.b)("reset",()=>{m=!1,Object(o.f)(h),localStorage.removeItem(u.A)})),Object(o.b)("init",()=>{const e=Object(l.d)(i),t=p(e)||e,n=Object(b.y)(t)||{};return window.history.replaceState(n,""),t});var O=n(0),j=n(49);const C=String(Date.now()+Math.random());let E;localStorage.setItem("tt-active-tab",C);const S=window.setInterval(()=>{E&&localStorage.getItem("tt-active-tab")!==C&&(E(),clearInterval(S))},2e3);var M=n(28),A=(n(74),n(75),n(76),n(24)),k=n(29),T=n(14);const P=["400 1em Roboto","500 1em Roboto"];function N(){if("fonts"in document)return Promise.all(P.map(e=>document.fonts.load(e)))}var D=n(48),L=n(12),F=n(8),B=(n(77),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),R=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function x(){const{listIds:e,byId:t}=Object(o.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(A.d)(n);return r?D.b(r,s.ApiMediaFormat.DataUri):void 0}))}const U={main:()=>Promise.all([Object(L.d)(L.a.Main,"Main").then(N),x()]),authPhoneNumber:()=>Promise.all([N(),Object(T.g)(B)]),authCode:()=>Object(T.g)(R),authPassword:()=>Object(T.g)(R),authQrCode:N};var _=Object(o.h)(e=>({uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(e.settings.byKey.customBackground),isCustomBackgroundColor:Boolean((e.settings.byKey.customBackground||"").match(/^#[a-f\d]{6,8}$/i)),isRightColumnShown:Object(b.V)(e)}),(e,t)=>Object(l.l)(t,["setIsUiReady"]))(({page:e,children:t,hasCustomBackground:n,isCustomBackgroundColor:r,isRightColumnShown:u,setIsUiReady:o})=>{const[c,d]=Object(M.a)(),{shouldRender:a,transitionClassNames:i}=Object(k.a)(!c,void 0,!0);return Object(O.n)(()=>{let t;return Promise.race([Object(f.e)(700),U[e]()]).then(()=>{d(),o({uiReadyState:1}),t=window.setTimeout(()=>{o({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),o({uiReadyState:0})}},[]),O.a.createElement("div",{id:"UiLoader"},t,a&&O.a.createElement("div",{className:Object(F.a)("mask",i)},"main"===e?O.a.createElement(O.a.Fragment,null,O.a.createElement("div",{className:"left"}),O.a.createElement("div",{className:Object(F.a)("middle",n&&!r&&"custom-bg-image",n&&r&&"custom-bg-color",u&&"with-right-column")}),u&&O.a.createElement("div",{className:"right"})):O.a.createElement("div",{className:"blank"})))}),G=n(18),$=n(25),W=n(41),z=n(40),H=n(16),K=n(46),V=n(37),q=n(56),Y=n(34),J=n(20);n(86);const Q=200+u.c;var Z=Object(O.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(O.q)(null),[o,c]=Object(O.r)(),[d,a]=Object(O.r)(G.a);function i(e){c(e),a(function(e=""){return e.length?G.a.filter(t=>Object(K.a)(t.name,e)):G.a}(e))}const s=Object(O.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=G.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),Q)},[r]),f=Object(O.m)(e=>{i(e.currentTarget.value)},[]),l=Object(O.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===o&&(n.value=""),i(n.value)},[o,t]);return O.a.createElement(q.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:c})=>{const d=()=>{if(c)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==o?o:t&&t.name||"";return O.a.createElement("div",{className:Object(F.a)("input-group",t&&"touched")},O.a.createElement("input",{ref:u,className:Object(F.a)("form-control",c&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:d,onFocus:d,onInput:f,onKeyDown:l}),O.a.createElement("label",null,"Country"),n?O.a.createElement(J.a,{color:"black"}):O.a.createElement("i",{onClick:d,className:Object(F.a)("css-icon-down",c&&"open")}))}},d.map(e=>O.a.createElement(Y.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},O.a.createElement("span",{"data-country-id":e.id}),O.a.createElement("span",{className:"country-flag"},Object(V.a)(e.flag,["hq_emoji"])),O.a.createElement("span",{className:"country-name"},e.name),O.a.createElement("span",{className:"country-code"},e.code))),!d.length&&O.a.createElement(Y.a,{key:"no-results",className:"no-results",disabled:!0},O.a.createElement("span",null,"No countries matched your filter.")))});let X=!1;var ee=Object(O.h)(Object(o.h)(e=>Object(l.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(l.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:o,authRememberMe:d,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(O.q)(null),[m,p]=Object(O.r)(),[g,y]=Object(O.r)(),[v,I]=Object(O.r)(!1),[w,j]=Object(O.r)(),C=m?`${m.code} ${g||""}`:g,E=C&&C.replace(/[^\d]+/g,"").length>=10;Object(O.n)(()=>{c.k||h.current.focus()},[m]),Object(O.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(O.n)(()=>{!a||m||v||p(Object(G.d)(a))},[m,a,v]);const S=Object(O.m)(e=>{const t=Object(G.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(G.b)(e,n))},[m]);Object(O.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(O.o)(()=>{h.current&&w&&h.current.setSelectionRange(...w)},[w]);const M=Object(O.m)(e=>{o&&l(),X||(X=!0,N(),Object(T.g)(R));const{value:t,selectionStart:n,selectionEnd:r}=e.target;j(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return O.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},O.a.createElement("div",{className:"auth-form"},O.a.createElement("div",{id:"logo"}),O.a.createElement("h2",null,"Sign in to Telegram"),O.a.createElement("p",{className:"note"},"Please confirm your country and",O.a.createElement("br",null),"enter your phone number."),O.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:C})}},O.a.createElement(Z,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),O.a.createElement(z.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:C,error:o,inputMode:"tel",onChange:M}),O.a.createElement(W.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(d),onChange:A}),E&&(k?O.a.createElement($.a,{type:"submit",ripple:!0,isLoading:r},"Next"):O.a.createElement(H.a,null)),k&&O.a.createElement($.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),te=n(17);var ne=()=>{const e=Object(te.a)(L.a.Auth,"AuthCode");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var re=()=>{const e=Object(te.a)(L.a.Auth,"AuthPassword");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var ue=()=>{const e=Object(te.a)(L.a.Auth,"AuthRegister");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var oe=()=>{const e=Object(te.a)(L.a.Auth,"AuthQrCode");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};n(87);var ce=Object(O.h)(Object(o.h)(e=>Object(l.l)(e,["authState"]),(e,t)=>Object(l.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(O.n)(()=>{t(),n()},[t,n]),Object(O.n)(()=>{},[]),e){case"authorizationStateWaitCode":return O.a.createElement(_,{page:"authCode",key:"authCode"},O.a.createElement(ne,null));case"authorizationStateWaitPassword":return O.a.createElement(_,{page:"authPassword",key:"authPassword"},O.a.createElement(re,null));case"authorizationStateWaitRegistration":return O.a.createElement(ue,null);case"authorizationStateWaitQrCode":return O.a.createElement(_,{page:"authQrCode",key:"authQrCode"},O.a.createElement(oe,null));case"authorizationStateWaitPhoneNumber":default:return O.a.createElement(_,{page:"authPhoneNumber",key:"authPhoneNumber"},O.a.createElement(ee,null))}}));var de=()=>{const e=Object(te.a)(L.a.Main,"Main");return e?O.a.createElement(e,null):void 0},ae=n.p+"app-inactive.96b2f485d4875a6b65899d8ae2825b97.png";n(88);var ie=()=>O.a.createElement("div",{id:"AppInactive"},O.a.createElement("div",{className:"content"},O.a.createElement("img",{src:ae,alt:""}),O.a.createElement("h3",{className:"title"},"Such error, many tabs"),O.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",O.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),O.a.createElement("div",{className:"actions"},O.a.createElement($.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function se(){return o.c.createElement(_,{page:"main",key:"main"},o.c.createElement(de,null))}var fe=Object(o.h)(e=>Object(l.l)(e,["authState","authIsSessionRemembered"]),(e,t)=>Object(l.l)(t,["disconnect"]))(({authState:e,authIsSessionRemembered:t,disconnect:n})=>{const[r,c]=Object(M.a)(!1);if(Object(O.n)(()=>{Object(j.b)(),E=()=>{n(),document.title=`${u.db}${u.D}`,c()}},[n,c]),r)return o.c.createElement(ie,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return o.c.createElement(ce,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return se()}return t?se():o.c.createElement(ce,null)});n(89);u.o&&console.log(">>> INIT"),Object(o.d)().init(),u.o&&console.log(">>> START INITIAL RENDER"),a.a.render(o.c.createElement(fe,null),document.getElementById("root")),u.o&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(o.e)())})}]); -//# sourceMappingURL=main.c7769ee2bb8655152f13.js.map \ No newline at end of file +!function(e){function t(t){for(var n,r,o=t[0],c=t[1],d=0,a=[];d=0&&I(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),O[n].renderTimes.push(t),O[n].renderCount++}}catch(t){Object(d.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const o=w(u);return e.$element=y(e,[o]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(d.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){return m(e)?M(e.children[0]):e.target}function A(e,t){m(e)?A(e.children[0],t):e.target=t}function k(e){const{cursor:t,byCursor:n}=f.hooks.state;var r;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(r=f,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,r.scheduleNextState&&r.forceUpdate||(r.scheduleNextState=Object(u.h)(()=>function(e){e.isMounted&&e.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue})}(r)),r.forceUpdate=Object(u.i)(()=>function(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}(r))),r.scheduleNextState(),r.forceUpdate())})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function T(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,o=f,c=()=>{if(!o.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(d.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(c):e(c),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return T(u.b,e,t)}function N(e,t){return T(u.d,e,t)}function D(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function L(e,t){return D(()=>e,t)}function F(e){return D(()=>({current:e}),[])}function B(e,t=c.a){return function(n){const r=F(n),u=F();return(!u.current||r.current&&!t(r.current,n))&&(r.current=n,u.current=g(e,n)),u.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(o.k)(Object.values(O),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"db",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return o})),n.d(t,"o",(function(){return c})),n.d(t,"q",(function(){return d})),n.d(t,"E",(function(){return a})),n.d(t,"p",(function(){return i})),n.d(t,"C",(function(){return s})),n.d(t,"z",(function(){return f})),n.d(t,"A",(function(){return l})),n.d(t,"y",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"M",(function(){return p})),n.d(t,"N",(function(){return g})),n.d(t,"O",(function(){return y})),n.d(t,"l",(function(){return v})),n.d(t,"F",(function(){return I})),n.d(t,"X",(function(){return O})),n.d(t,"T",(function(){return j})),n.d(t,"U",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"j",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"mb",(function(){return k})),n.d(t,"W",(function(){return T})),n.d(t,"x",(function(){return P})),n.d(t,"Q",(function(){return N})),n.d(t,"P",(function(){return D})),n.d(t,"eb",(function(){return L})),n.d(t,"Bb",(function(){return F})),n.d(t,"a",(function(){return B})),n.d(t,"e",(function(){return R})),n.d(t,"d",(function(){return x})),n.d(t,"r",(function(){return U})),n.d(t,"t",(function(){return _})),n.d(t,"u",(function(){return G})),n.d(t,"v",(function(){return $})),n.d(t,"jb",(function(){return W})),n.d(t,"ib",(function(){return z})),n.d(t,"Z",(function(){return H})),n.d(t,"Y",(function(){return K})),n.d(t,"cb",(function(){return V})),n.d(t,"bb",(function(){return q})),n.d(t,"ab",(function(){return Y})),n.d(t,"I",(function(){return J})),n.d(t,"c",(function(){return Q})),n.d(t,"tb",(function(){return Z})),n.d(t,"ub",(function(){return X})),n.d(t,"ob",(function(){return ee})),n.d(t,"pb",(function(){return te})),n.d(t,"wb",(function(){return ne})),n.d(t,"sb",(function(){return re})),n.d(t,"xb",(function(){return ue})),n.d(t,"yb",(function(){return oe})),n.d(t,"vb",(function(){return ce})),n.d(t,"zb",(function(){return de})),n.d(t,"qb",(function(){return ae})),n.d(t,"rb",(function(){return ie})),n.d(t,"R",(function(){return se})),n.d(t,"S",(function(){return fe})),n.d(t,"nb",(function(){return le})),n.d(t,"H",(function(){return be})),n.d(t,"k",(function(){return he})),n.d(t,"fb",(function(){return me})),n.d(t,"hb",(function(){return pe})),n.d(t,"gb",(function(){return ge})),n.d(t,"lb",(function(){return ye})),n.d(t,"b",(function(){return ve})),n.d(t,"g",(function(){return Ie})),n.d(t,"K",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"kb",(function(){return je})),n.d(t,"G",(function(){return Ce})),n.d(t,"Ab",(function(){return Ee})),n.d(t,"w",(function(){return Se})),n.d(t,"m",(function(){return Me})),n.d(t,"n",(function(){return Ae})),n.d(t,"s",(function(){return ke}));const r="Telegram",u=" [Inactive]",o="Telegram WebZ alpha 8ae9802",c=!1,d=!1,a=!1,i="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",s="GramJs:sessionId",f=!1,l="tt-global-state",b=30,h=5e3,m=!1,p="tt-media",g="tt-media-avatars",y="tt-media-progressive",v="tt-custom-bg",I="tt-lang-packs",w=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),O=1,j=750,C=w?60:40,E=2*C,S=72,M=w?30:25,A=100,k=42,T=42,P=20,N=30,D=200,L=500,F=25,B=!1,R=2,x=R,U=16,_=1e4,G="editable-message-text",$="editable-message-text-modal",W=1440,z=1150,H=1275,K=925,V=600,q=950,Y=450,J=1e9,Q=100,Z=13,X=11,ee=160,te=120,ne=64,re=48,ue=32,oe=64,ce=64,de=160,ae=140,ie=80,se="MEMOJI_STICKER",fe=200,le=450,be=450,he="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",me="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",pe=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ge=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ye=777e3,ve=0,Ie=1,we=10,Oe=5,je=2147483646,Ce=["android","ios"],Ee="TelegramTips",Se="https://bugs.telegram.org/?tag_ids=41&sort=time",Me="#0F0F0F",Ae="#0a0a0a8c",ke="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return y})),n.d(t,"e",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"b",(function(){return w})),n.d(t,"a",(function(){return O})),n.d(t,"f",(function(){return j})),n.d(t,"h",(function(){return C}));var r=n(0),u=n(1),o=n(31),c=n(22),d=n(9),a=n(26),i=n(3),s=n(21);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;const g=Object(d.i)((function(){h.forEach(e=>e(l))}));function y(e){"object"==typeof e&&e!==l&&(l=e,g())}function v(){return l}function I(){return m}function w(e,t){b[e]||(b[e]=[],m[e]=t=>{!function(e,t){b[e]&&b[e].forEach(e=>{const n=e(l,m,t);n&&y(n)})}(e,t)}),b[e].push(t)}function O(e){h.push(e)}function j(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function C(e=(()=>({})),t=(()=>({}))){return n=>function(u){const[d]=Object(r.r)(Object(c.a)(p)),i=Object(o.a)();Object(r.n)(()=>()=>{p.delete(d)},[d]);let b=p.get(d);if(b||(b={mapStateToProps:e,mapReducersToProps:t,ownProps:u,areMappedPropsChanged:!1,forceUpdate:i,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(d,b)),b.areMappedPropsChanged&&(b.areMappedPropsChanged=!1),!b.mappedProps||!Object(a.a)(b.ownProps,u)){b.ownProps=u;try{b.mappedProps={...e(l,u),...t(y,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},b.mappedProps,u))}}function E(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?["LENGTH"]:n.filter(n=>e[n]!==t[n])}u.o&&(window.getGlobal=v,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function o(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function c(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function d(e,t){const n=new Set(t.map(String));return o(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,o]=Array.isArray(n)?n:[n,n],[c,d]=t;let a,i;if("function"==typeof c?(a=c(e)||0,i=c(r)||0):"string"==typeof c&&(a=e[c]||0,i=r[c]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof d?(t=d(e)||0,n=d(r)||0):"string"==typeof d&&(t=e[d]||0,n=r[d]||0),"asc"===o?t-n:n-t}}let u,o;return"function"==typeof t?(u=t(e)||0,o=t(r)||0):"string"==typeof t&&(u=e[t]||0,o=r[t]||0),"asc"===n?u-o:o-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return o})),n.d(t,"m",(function(){return c})),n.d(t,"j",(function(){return d})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";var r=n(59);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(60);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var o=n(61);n.d(t,"ApiMessageEntityTypes",(function(){return o.a})),n.d(t,"MAIN_THREAD_ID",(function(){return o.b})),n.d(t,"MESSAGE_DELETED",(function(){return o.c}));var c=n(62);n.o(c,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return c.ApiMediaFormat}));var d=n(63);n.d(t,"ApiMediaFormat",(function(){return d.a}));n(64),n(65)},function(e,t,n){"use strict";n.d(t,"X",(function(){return r.b})),n.d(t,"Y",(function(){return r.c})),n.d(t,"Z",(function(){return r.d})),n.d(t,"wb",(function(){return r.g})),n.d(t,"ob",(function(){return r.e})),n.d(t,"vb",(function(){return r.f})),n.d(t,"Cb",(function(){return r.h})),n.d(t,"W",(function(){return r.a})),n.d(t,"kb",(function(){return u.w})),n.d(t,"jb",(function(){return u.v})),n.d(t,"hb",(function(){return u.t})),n.d(t,"mb",(function(){return u.y})),n.d(t,"ib",(function(){return u.u})),n.d(t,"nb",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"T",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"lb",(function(){return u.x})),n.d(t,"fb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"xb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"J",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"gb",(function(){return u.s})),n.d(t,"d",(function(){return u.b})),n.d(t,"Ab",(function(){return u.C})),n.d(t,"zb",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"eb",(function(){return u.q})),n.d(t,"I",(function(){return u.n})),n.d(t,"Bb",(function(){return u.D})),n.d(t,"A",(function(){return i})),n.d(t,"yb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"M",(function(){return l})),n.d(t,"N",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"K",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"sb",(function(){return g})),n.d(t,"tb",(function(){return y})),n.d(t,"pb",(function(){return v})),n.d(t,"cb",(function(){return I})),n.d(t,"ub",(function(){return w})),n.d(t,"db",(function(){return O})),n.d(t,"U",(function(){return j})),n.d(t,"V",(function(){return C})),n.d(t,"rb",(function(){return E})),n.d(t,"qb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"bb",(function(){return T})),n.d(t,"G",(function(){return P})),n.d(t,"O",(function(){return N})),n.d(t,"t",(function(){return D})),n.d(t,"u",(function(){return L})),n.d(t,"L",(function(){return F})),n.d(t,"y",(function(){return B})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return x})),n.d(t,"P",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"E",(function(){return G})),n.d(t,"D",(function(){return $})),n.d(t,"C",(function(){return z})),n.d(t,"B",(function(){return H})),n.d(t,"b",(function(){return V})),n.d(t,"i",(function(){return q})),n.d(t,"R",(function(){return Y})),n.d(t,"S",(function(){return J})),n.d(t,"ab",(function(){return Q})),n.d(t,"s",(function(){return Z})),n.d(t,"w",(function(){return X})),n.d(t,"r",(function(){return ee})),n.d(t,"a",(function(){return te}));var r=n(23),u=n(24),o=n(4),c=n(1),d=n(58);const a=new RegExp(c.fb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t=!1){const{text:n,photo:r,video:u,audio:o,voice:c,document:d,sticker:a,contact:i,poll:s,invoice:f}=e.content;if(e.groupedId)return n?`${t?"":"🖼 "}${n.text}`:"Album";if(r)return n?`${t?"":"🖼 "}${n.text}`:"Photo";if(u)return u.isGif?n?`${t?"":"GIF "}${n.text}`:"GIF":n?`${t?"":"📹 "}${n.text}`:"Video";if(a)return"Sticker "+a.emoji;if(o){const e=[o.title,o.performer].filter(Boolean).join(" — ")||n&&n.text;return e?"🎧 "+e:"Audio"}return c?n?`${t?"":"🎤 "}${n.text}`:"Voice Message":d?`${t?"":"📎 "}${n?n.text:d.fileName}`:i?"Contact":s?"📊 "+s.summary.question:f?"Invoice":n?n.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:o,voice:c,document:d,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||o||c||d||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:o,voice:c,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||o||c||a||i||s||f)&&(Object(d.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===o.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===o.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function I(e){return!!e.content.action}function w(e){return e.chatId===c.lb&&E(e)}function O(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e){return e.id>0?Object(r.c)(e):Object(u.i)(e)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=c.I}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(53);function k(e){return e.content}function T(e){return Boolean(P(e)||N(e)||B(e)||F(e)||function(e){return e.content.contact}(e)||R(e)||D(e)||L(e)||function(e){return e.content.voice}(e))}function P(e){return e.content.photo}function N(e){return e.content.video}function D(e){return e.content.action}function L(e){return e.content.audio}function F(e){return e.content.sticker}function B(e){return e.content.document}function R(e){return e.content.poll}function x(e){return e.content.invoice}function U(e){return e.content.webPage}function _(e){const t=U(e);return t?t.photo:void 0}function G(e){const t=function(e){const t=P(e)||N(e)||B(e)||F(e)||_(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function $(e,t){const{photo:n,video:r,sticker:u,audio:o,voice:c,document:d}=e.content,a=_(e);if(!(n||r||u||a||o||c||d))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(K(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(K(e))return;return V(r)?W(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return W(r,s);case"download":return s+"?download"}if(d)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(d)||K(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(o)switch(t){case"micro":case"pictogram":return;default:return W(o,s)}if(c)switch(t){case"micro":case"pictogram":return;default:return s}}function W(e,t){return M.h&&M.i?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function z(e,t){const{sticker:n,video:r,audio:u,voice:c}=e.content;return n&&"inline"===t&&n.isAnimated?o.ApiMediaFormat.Lottie:r&&M.h&&("viewerFull"===t||"inline"===t&&V(r))?o.ApiMediaFormat.Progressive:u||c?c&&!M.g?o.ApiMediaFormat.BlobUrl:o.ApiMediaFormat.Progressive:o.ApiMediaFormat.BlobUrl}function H(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function K(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function V(e){return e.isGif||e.isRound||e.size<=10485760}function q(e,t,n=!1){const r=X(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||J(e)}function J(e){return e.sizes.find(e=>"x"===e.type)||e.sizes.find(e=>"m"===e.type)||e.sizes.find(e=>"s"===e.type)||e.thumbnail}function Q(e){if(e.width&&e.height)return e}function Z(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function X(e,t,n){let r;switch(n){case"media":r=e=>{const t=N(e);return P(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=B;break;case"links":r=e=>U(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=L;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function ee(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function te(e,t){return`${e}_${t}`}n(54)},function(e,t,n){"use strict";n.d(t,"S",(function(){return Pe})),n.d(t,"kb",(function(){return Ne})),n.d(t,"V",(function(){return De})),n.d(t,"Db",(function(){return a})),n.d(t,"f",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"O",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"xb",(function(){return b})),n.d(t,"n",(function(){return h})),n.d(t,"g",(function(){return m})),n.d(t,"K",(function(){return p})),n.d(t,"d",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"j",(function(){return v})),n.d(t,"i",(function(){return I})),n.d(t,"M",(function(){return w})),n.d(t,"h",(function(){return O})),n.d(t,"q",(function(){return j})),n.d(t,"y",(function(){return T})),n.d(t,"r",(function(){return P})),n.d(t,"m",(function(){return N})),n.d(t,"nb",(function(){return D})),n.d(t,"X",(function(){return F})),n.d(t,"db",(function(){return B})),n.d(t,"x",(function(){return R})),n.d(t,"Eb",(function(){return x})),n.d(t,"gb",(function(){return U})),n.d(t,"lb",(function(){return _})),n.d(t,"ob",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"C",(function(){return W})),n.d(t,"E",(function(){return z})),n.d(t,"B",(function(){return H})),n.d(t,"bb",(function(){return K})),n.d(t,"zb",(function(){return V})),n.d(t,"F",(function(){return q})),n.d(t,"Ab",(function(){return Y})),n.d(t,"Bb",(function(){return J})),n.d(t,"yb",(function(){return Q})),n.d(t,"a",(function(){return Z})),n.d(t,"W",(function(){return X})),n.d(t,"k",(function(){return ee})),n.d(t,"mb",(function(){return te})),n.d(t,"D",(function(){return ne})),n.d(t,"l",(function(){return re})),n.d(t,"H",(function(){return ue})),n.d(t,"T",(function(){return oe})),n.d(t,"cb",(function(){return ce})),n.d(t,"qb",(function(){return de})),n.d(t,"J",(function(){return ae})),n.d(t,"b",(function(){return ie})),n.d(t,"e",(function(){return se})),n.d(t,"Cb",(function(){return fe})),n.d(t,"ib",(function(){return le})),n.d(t,"G",(function(){return be})),n.d(t,"Q",(function(){return he})),n.d(t,"p",(function(){return me})),n.d(t,"R",(function(){return pe})),n.d(t,"U",(function(){return ge})),n.d(t,"I",(function(){return ye})),n.d(t,"Z",(function(){return ve})),n.d(t,"P",(function(){return Ie})),n.d(t,"pb",(function(){return we})),n.d(t,"ab",(function(){return Oe})),n.d(t,"rb",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"tb",(function(){return Ee})),n.d(t,"t",(function(){return Le})),n.d(t,"A",(function(){return Se})),n.d(t,"w",(function(){return Me})),n.d(t,"v",(function(){return Ae})),n.d(t,"Y",(function(){return ke})),n.d(t,"u",(function(){return Te})),n.d(t,"z",(function(){return E})),n.d(t,"s",(function(){return S})),n.d(t,"ub",(function(){return M})),n.d(t,"vb",(function(){return A})),n.d(t,"c",(function(){return k})),n.d(t,"eb",(function(){return Fe})),n.d(t,"fb",(function(){return Be})),n.d(t,"hb",(function(){return Re})),n.d(t,"wb",(function(){return xe}));var r=n(19),u=n(7),o=n(4),c=n(1),d=n(5);function a(e,t){return e.users.byId[t]}function i(e,t){return e.chats.byId[t]}function s(e,t){const n=Object(d.T)(t);return!!n&&a(e,n)}function f(e,t){return t===e.currentUserId}function l(e,t){const n=s(e,t);return n&&Object(d.vb)(n)}function b(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function h(e,t){if(!Object(d.kb)(t.id)&&!Object(d.ib)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==c.P?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(d.wb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function m(e,t){const n=i(e,t),r=n&&Object(d.T)(n),u=r&&a(e,r);if(u&&Object(d.vb)(u))return u}function p(e,t){const n=i(e,t),r=m(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(d.qb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:c}=u.threadsById[o.MAIN_THREAD_ID]||{};return c&&!c.length}function g(e){return Boolean(e.chats.listIds.active)}function y(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some(e=>e&&e.includes(t))}function v(e,t){const n=i(e,t);if(n&&y(e,t))return n.folderId===c.g?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function w(e,t,n=c.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===c.b)return!!r&&r.includes(t);if(n===c.g)return!!u&&u.includes(t);const{byId:o}=e.chatFolders,{pinnedChatIds:d}=o[n]||{};return!!d&&d.includes(t)}function O(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function j(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((e,t)=>{const r=n[t];return r&&r.unreadCount&&!r.isMuted?e+r.unreadCount:e},0)}var C=n(3);function E(e){return e.stickers.search}function S(e){return e.gifs.search}function M(e,t){return e.stickers.setsById[t]}function A(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function k(e,t){const{animatedEmojis:n}=e;if(n&&n.stickers)return t=t.replace("️",""),n.stickers.find(e=>e.emoji===t)}function T(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function P(e){const{chatId:t}=T(e)||{};return t?i(e,t):void 0}function N(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function D(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function L(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const o=u.threadsById[n];return o?o[r]:void 0}function F(e,t,n){return L(e,t,n,"listedIds")}function B(e,t,n){return L(e,t,n,"outlyingIds")}function R(e,t,n,r){switch(r){case"thread":return x(e,t,n);case"pinned":return U(e,t);case"scheduled":return _(e,t)}}function x(e,t,n){return L(e,t,n,"viewportIds")}function U(e,t){return L(e,t,o.MAIN_THREAD_ID,"pinnedIds")}function _(e,t){return L(e,t,o.MAIN_THREAD_ID,"scheduledIds")}function G(e,t,n){return L(e,t,n,"scrollOffset")}function $(e,t,n){return L(e,t,n,"replyingToId")}function W(e,t,n){return L(e,t,n,"editingId")}function z(e,t){return L(e,t,o.MAIN_THREAD_ID,"editingScheduledId")}function H(e,t,n){return L(e,t,n,"draft")}function K(e,t,n){return L(e,t,n,"noWebPage")}function V(e,t,n){return L(e,t,n,"threadInfo")}function q(e,t,n){return L(e,t,n,"firstMessageId")}function Y(e,t,n){if(n===o.MAIN_THREAD_ID)return i(e,t);const r=V(e,t,n);return r?i(e,r.originChannelId||t):void 0}function J(e,t,n){if(n===o.MAIN_THREAD_ID)return;const r=V(e,t,n);return r?r.topMessageId:void 0}function Q(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:o}=n;return u||o?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||o&&o===e.threadInfo.topMessageId)):void 0}function Z(e,t,n){const r=T(e);if(!r)return!1;const{threadInfo:u}=Q(e,t,n)||{};return t===r.chatId&&(r.threadId===o.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function X(e,t,n){const r=x(e,t,n);if(!r||!r.length)return!0;let u;if(n===o.MAIN_THREAD_ID){const n=i(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=V(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=c.I&&!ee(e,t,u)||r[r.length-1]>=u}function ee(e,t,n){const r=N(e,t);return r?r[n]:void 0}function te(e,t,n){const r=D(e,t);return r?r[n]:void 0}function ne(e,t,n,r){if("scheduled"===r){const n=z(e,t);return n?te(e,t,n):void 0}{const r=W(e,t,n);return r?ee(e,t,r):void 0}}function re(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find(e=>e.content.poll&&e.content.poll.id===t),n)break}return n}function ue(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function oe(e,t){const n=ue(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ce(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=i(e,t.chatId)||{};return Object(d.rb)(t)||!n||n0?a(e,n):i(e,n)}function ae(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?i(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function ie(e,t,n){const r=i(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(d.kb)(r.id),o=f(e,t.chatId),c=Object(d.hb)(r),a=Object(d.mb)(r),s=Object(d.ib)(r),l=Object(d.ub)(t),b=Object(d.sb)(t),h=Object(d.cb)(t),{content:m}=t,p=(o||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(d.pb)(t)&&!t.viaBotId,g=Object(d.e)(r,n)&&!l,y=u||r.isCreator||!s&&!Object(d.xb)(r,"pinMessages")||Object(d.q)(r,"pinMessages");let v=!h&&y,I=!1;const w=U(e,r.id);v&&(I=Boolean(w&&w.includes(t.id)),v=!I);const O=u||b||c||r.isCreator||Object(d.q)(r,"deleteMessages"),j=O&&!l&&(u&&!o||c&&(b||Object(d.q)(r,"deleteMessages"))),C=!h&&p&&(b||s&&(r.isCreator||Object(d.q)(r,"editMessages"))),E=!h&&!l,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,P=!h&&(s||a),N=!h;return{noOptions:[g,C,v,I,O,j,E,A,k,T,P,N].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:I,canDelete:O,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:P,canSelect:N}}function se(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=T(e)||{},u=n&&N(e,n);if(!u||!t||!r)return{};const o=t.map(t=>u[t]&&ie(e,u[t],r)).filter(Boolean);return{canDelete:o.every(e=>e.canDelete),canDeleteForAll:o.every(e=>e.canDeleteForAll)}}function fe(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function le(e,t,n){if(n===o.MAIN_THREAD_ID){const n=i(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(d.rb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=V(e,t,n);if(!r)return;return r.lastReadInboxMessageId?r.lastMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId):r.lastReadInboxMessageId:r.topMessageId}}function be(e,t,n){if(n===o.MAIN_THREAD_ID){if(!i(e,t))return}else{const r=V(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const r=B(e,t,n),u=F(e,t,n),c=N(e,t);if(!c||!r&&!u)return;const d=le(e,t,n);if(r){const e=r.find(e=>!d||e>d&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled));if(e)return e}if(u){const e=u.find(e=>!d||e>d&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled));if(e)return e}}function he(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function me(e,t){const n=Object.values(e.chats.byId).find(e=>Object(d.nb)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=i(e,Number(n));return u&&Object(d.nb)(u)&&r[u.id].byId[t]}))}function pe(e){const{selectedMessages:t}=e;return Boolean(t)}function ge(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function ye(e,t,n){const r=N(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function ve(e,t,n){const r=N(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function Ie(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=ve(e,t,n);return u&&u.every(e=>r.includes(e))}function we(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Oe(e,t){const n=i(e,t);if(!n)return;if(!l(e,n))return;const r=N(e,t),u=x(e,t,o.MAIN_THREAD_ID);if(!r||!u)return;const c=Object(C.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),d=Object(C.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return c&&d&&d>c?void 0:c?r[c]:void 0}function je(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:o,shouldAutoDownloadMediaInGroups:c,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(o&&Object(d.kb)(n.id)||c&&Object(d.jb)(n)||a&&Object(d.ib)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Ce(e,t){const n=Object(d.O)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,o=n.isGif||n.isRound;return r&&!o||u&&o}function Ee(e){return e.settings.byKey.shouldLoopStickers}function Se(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;const r=Object(d.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Me(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=T(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ae(e){const t=Me(e);if(t)return e.localMediaSearch.byChatId[t]}function ke(e,t){return e.management.byChatId[t]}function Te(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;if(Object(d.kb)(t))return"user";const r=i(e,t);return r?Object(d.jb)(r)?"group":"channel":void 0}function Pe(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Ne(e){const{users:t,isChatInfoShown:n}=e,o=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),c=Boolean(!u.f&&Se(e)),d=function(e){const{chatId:t,threadId:n}=T(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==E(e).query,i=void 0!==S(e).query,{chatId:s}=T(e)||{},f=t.selectedId,l=g(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return o?r.l.PollResults:c?r.l.Search:d?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function De(e){return void 0!==Ne(e)}function Le(e){return e.globalSearch.query}function Fe(e){return e.payment.messageId}function Be(e){return e.payment.formId}function Re(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function xe(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"n",(function(){return u})),n.d(t,"e",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"b",(function(){return d})),n.d(t,"i",(function(){return a})),n.d(t,"k",(function(){return i})),n.d(t,"f",(function(){return s})),n.d(t,"l",(function(){return f})),n.d(t,"c",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"h",(function(){return h})),n.d(t,"g",(function(){return m})),n.d(t,"a",(function(){return p})),n.d(t,"m",(function(){return g})),n.d(t,"o",(function(){return v}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),o="Mac OS"===u,c="iOS"===u,d="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.cb||window.innerWidth<=r.bb&&window.innerHeight<=r.ab,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(o||c)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=window.devicePixelRatio||1,g=c;let y;function v(){return Boolean(y)}new Promise(e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n}).then(e=>{y=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...o)=>{u?(clearTimeout(u),u=void 0):n&&e(...o),u=self.setTimeout(()=>{r&&e(...o),u=void 0},t)}}function u(e,t,n=!0){let r,u,o;return(...c)=>{u=!0,o=c,r||(n&&(u=!1,e(...o)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...o)},t))}}function o(e){return a(h,e)}function c(e){return a(m,e)}function d(e){return a(i,e)}function a(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function i(e){Promise.resolve().then(e)}function s(e){self.requestIdleCallback?self.requestIdleCallback(e):i(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return o})),n.d(t,"h",(function(){return c})),n.d(t,"j",(function(){return d})),n.d(t,"d",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"b",(function(){return h}));const f=e=>new Promise(t=>{setTimeout(()=>t(),e)});function l(){return new Promise(e=>{requestAnimationFrame(e)})}let b;function h(e,t=!1){b?t?b.unshift(e):b.push(e):(b=[e],requestAnimationFrame(()=>{const e=b;b=void 0,e.forEach(e=>e())}))}function m(e){return h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(70),u=n.n(r),o=n(1),c=n(22);let d;const a=new Map,i=new Map;function s(e,t=""){return d||(o.o&&console.log(">>> START LOAD WORKER"),d=new u.a,function(e){d.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(d)return b({type:"callMethod",name:e,args:t});o.o&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&d.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(c.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),d.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return y})),n.d(t,"c",(function(){return O})),n.d(t,"b",(function(){return j}));var r=n(1),u=n(13),o=n(10);var c=n(3),d=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(44);const b={en:d,es:a,it:i,pl:s,ru:f},h=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],m={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},p=new Map;let g;const{addCallback:y,removeCallback:v,runCallbacks:I}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let w;async function O(e,t){if(g&&e===w)return document.documentElement.lang=e,void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(o.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(n){if(b[e])try{const t=await fetch(b[e]),r=await t.json(),u=Object(c.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.o&&console.error(e)}p.clear(),w=e,g=n,document.documentElement.lang=e,t&&t(),I(g)}}function j(e,t,n){if(void 0!==t){const r=p.get(`${e}_${t}_${n}`);if(r)return r}if(!g)return e;const r=g[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=w&&m[w]?m[w](e):0;return h[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return p.set(`${e}_${t}_${n}`,r),r}return u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const o={},c={};async function d(e,t){if(!o[e]){switch(e){case u.Auth:o[u.Auth]=n.e(4).then(n.bind(null,93));break;case u.Main:r.o&&console.log(">>> START LOAD MAIN BUNDLE"),o[u.Main]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,91));break;case u.Extra:o[u.Extra]=Promise.all([n.e(0),n.e(2)]).then(n.bind(null,92))}o[e].then(f)}const d=await o[e];return c[e]||(c[e]=d),a(e,t)}function a(e,t){const n=c[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"b",(function(){return d}));const r=self.caches;let u;async function o(e,t,n){if(r)try{const o=new Request(t),c=await r.open(e),d=await c.match(o);if(!d)return;switch(n){case u.Text:return await d.text();case u.Blob:{const e=await d.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=d.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await d.json();default:return}}catch(e){return void console.warn(e)}}async function c(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),o=new Request(t),c=new Response(u),d=await r.open(e);return await d.put(o,c)}catch(e){return void console.warn(e)}}async function d(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return d})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function o(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const o=new Uint8Array(u);for(;u--;)o[u]=r.charCodeAt(u);return new Blob([o],{type:n})}function c(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)})}function d(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)})])}async function f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function o(e){return e.indexOf(u)<0?e.replace(r,""):e}t.a=/(?:\u2624|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},function(e,t,n){"use strict";var r=n(0),u=n(20);n(82);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(12),o=n(31);t.a=(e,t,n=!1,c=!1)=>{const d=Object(u.c)(e,t),a=Object(o.a)();return c&&Object(u.b)(a),Object(r.n)(()=>{n||d||Object(u.d)(e,t).then(a)},[e,a,d,t,n]),d}},function(e,t,n){"use strict";n.d(t,"d",(function(){return c})),n.d(t,"e",(function(){return d})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var o="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function c(e){return o.find(t=>t.id===e)}function d(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=o.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,o,c)=>{const d=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${d}${u}`),o&&(a+=`${d}${o}`),c&&(a+=`${d}${c}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=d(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";let r,u,o,c,d,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return o})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return d})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(o||(o={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(c||(c={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(d||(d={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(78);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",d),window.addEventListener("unhandledrejection",d);const o=Date.now();let c=!1;function d(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!c){if(Date.now()-o<=5e3){if(localStorage.getItem(r.A))localStorage.removeItem(r.A);else{if(!localStorage.getItem(r.C))return;localStorage.removeItem(r.C)}return c=!0,void window.location.reload()}0}}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(30),o=n(3);const c=[1,8,5,2,7,4,6];function d(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(e.id===r.lb)return t("ServiceNotifications").toLowerCase();if(e.type&&"userTypeBot"===e.type)return"bot";if(!e.status)return"";switch(e.status.type){case"userStatusEmpty":return t("ALongTimeAgo");case"userStatusLastMonth":return t("WithinAMonth");case"userStatusLastWeek":return t("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=e.status;if(!n)return t("LastSeen.Offline");const r=new Date,o=new Date(1e3*n);if(o>=r)return t("LastSeen.JustNow");const c=new Date(r.getTime()-o.getTime());if(c.getTime()/1e3<60)return t("LastSeen.JustNow");if(c.getTime()/1e3<3600){return t("LastSeen.MinutesAgo",Math.floor(c.getTime()/1e3/60))}const d=new Date;if(d.setHours(0,0,0,0),o>d){if(c.getTime()/1e3<21600){return t("LastSeen.HoursAgo",Math.floor(c.getTime()/1e3/60/60))}return t("LastSeen.TodayAt",Object(u.h)(o))}const a=new Date;return a.setDate(r.getDate()-1),d.setHours(0,0,0,0),o>a?t("LastSeen.YesterdayAt",Object(u.h)(o)):t("LastSeen.AtDate",Object(u.b)(o))}case"userStatusOnline":return t("Online");case"userStatusRecently":return t("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.lb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.lb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(o.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return c[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return a})),n.d(t,"v",(function(){return i})),n.d(t,"t",(function(){return s})),n.d(t,"y",(function(){return f})),n.d(t,"u",(function(){return l})),n.d(t,"z",(function(){return b})),n.d(t,"j",(function(){return h})),n.d(t,"p",(function(){return m})),n.d(t,"i",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"f",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"x",(function(){return I})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return j})),n.d(t,"c",(function(){return C})),n.d(t,"a",(function(){return E})),n.d(t,"o",(function(){return S})),n.d(t,"h",(function(){return M})),n.d(t,"g",(function(){return A})),n.d(t,"s",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return P})),n.d(t,"B",(function(){return N})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return L})),n.d(t,"q",(function(){return F})),n.d(t,"n",(function(){return B})),n.d(t,"D",(function(){return R}));var r=n(4),u=n(1),o=n(3),c=n(23),d=n(11);function a(e){return e>0}function i(e){return s(e)||f(e)}function s(e){return"chatTypeBasicGroup"===e.type}function f(e){return"chatTypeSuperGroup"===e.type}function l(e){return"chatTypeChannel"===e.type}function b(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function h(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function m(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function p(e,t,n=!1){return n||t&&e.id===t.id&&t.isSelf?Object(d.b)("SavedMessages"):e.title||Object(d.b)("HiddenName")}function g(e){if(e.fullInfo)return e.fullInfo.about}function y(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function v(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function I(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function j(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function C(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!a(e.id)||(l(e)?O(e,"postMessages"):w(e)||!j(e,"sendMessages"))))}function E(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!j(e,"sendMedia"),canAttachPolls:(n||!j(e,"sendPolls"))&&(!a(e.id)||t),canSendStickers:n||!j(e,"sendStickers"),canSendGifs:n||!j(e,"sendGifs"),canAttachEmbedLinks:n||!j(e,"embedLinks")}}function S(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function M(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function A(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function k(e){return e.folderId===u.g}function T(e){return s(e)||(f(e)||l(e))&&e.isCreator}function P(e,t,n,r){const u=n.excludedChatIds?new Set(n.excludedChatIds):void 0,o=n.excludedChatIds?new Set(n.includedChatIds):void 0,c=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(r||Object.keys(e).map(Number)).filter(r=>function(e,t,n,r,u,o){if(r&&r.has(e.id))return!1;if(u&&u.has(e.id))return!0;if(o&&o.has(e.id))return!0;if(k(e)&&t.excludeArchived)return!1;if(e.isMuted&&t.excludeMuted)return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(a(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(i(e))return!!t.groups;if(l(e))return!!t.channels}return!1}(e[r],n,t,u,o,c)),n.pinnedChatIds]}function N(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(k(e))return!1;break;case"archived":if(!k(e))return!1}return!e.isRestricted&&!e.isNotJoined}const c=t.map(t=>e[t]).filter(u),d=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>d.has(e.id)):[],otherChats:Object(o.k)(n?c.filter(e=>!n.includes(e.id)):c,A,"desc")}}function D(e,t,n,r){const[u]=P(e,t,n,r),o=u.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:o.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:o.some(e=>e.unreadMentionsCount||!e.isMuted&&(e.unreadCount||e.hasUnreadMark))}}function L(e,t,n,r,u){const{id:o,title:c,emoticon:d,description:a,pinnedChatIds:i,excludedChatIds:s,includedChatIds:f,excludeArchived:l,excludeMuted:b,excludeRead:h,...m}=n;if(Object.values(m).filter(Boolean).length>1||s&&s.length||f&&f.length){return u("Chats",function(e,t,n,r){const[u,o]=P(e,t,n,r),{pinnedChats:c,otherChats:d}=N(e,u,o,"folder");return c.length+d.length}(e,t,n,r))}return m.bots?u("FilterBots"):m.groups?u("FilterGroups"):m.channels?u("FilterChannels"):m.contacts?u("FilterContacts"):m.nonContacts?u("FilterNonContacts"):void 0}function F(e){return!!e&&e.id<0}function B(e,t){if(t&&!a(e))return t.isSelf?"You":Object(c.b)(t)}function R(e,t,n=!1,r){return Object(o.k)(e,e=>{const u=t[e];if(!u)return 0;let o=0;return u.lastMessage&&(o+=u.lastMessage.date),n&&u.isVerified&&(o+=3e9),r&&r.includes(e)&&(o+=Date.now()+(r.length-r.indexOf(e))),o},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),o=n(20),c=n(35);n(80);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:d,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:I,ariaLabel:w,href:O,download:j,disabled:C,ripple:E,faded:S,tabIndex:M})=>{let A=Object(r.q)(null);e&&(A=e);const[k,T]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",I&&"loading",E&&"has-ripple",S&&"faded",k&&"clicked"),N=Object(r.m)(e=>{!C&&n&&n(e),T(!0),setTimeout(()=>{T(!1)},400)},[C,n]),D=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return O?r.a.createElement("a",{ref:A,className:P,href:O,title:w,download:j,tabIndex:M},l,!C&&E&&r.a.createElement(c.a,null)):r.a.createElement("button",{ref:A,type:t,className:P,onClick:N,onContextMenu:d,onMouseDown:D,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":w,title:w,tabIndex:M},I?r.a.createElement("div",null,r.a.createElement("span",null,"Please wait.."),r.a.createElement(o.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(c.a,null))}},function(e,t,n){"use strict";function r(e,t){const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[n]===t[n])}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),o={},c=new Map,d={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){d[e]||(d[e]=0,document.addEventListener(e,h));(function(e){o[e]||(o[e]=new Map);return o[e]})(e).set(t,n),function(e){const t=c.get(e);if(t)return t;const n=new Set;return c.set(e,n),n}(t).add(e),d[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){d[e]--,d[e]||document.removeEventListener(e,h),o[e].delete(t),c.get(t).delete(e)}function b(e){const t=c.get(e);t&&(t.forEach(t=>l(t,e)),c.delete(e))}function h(e){const t=o[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},o=()=>{e.preventDefault()},c=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?o:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(c),n))return;r=r.parentNode}}}r.o&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:o,delegatedEventsByElement:c,documentEventCounters:d})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,o="fast",c=!1)=>{const[d,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(!1);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),d||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},c?0:350)));const l=s||e&&n,b=Boolean(i.current),h=e||b;return{shouldRender:h,transitionClassNames:Object(u.a)(o&&"opacity-transition",o,l&&"open",h&&"shown",b&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return d})),n.d(t,"k",(function(){return a})),n.d(t,"n",(function(){return i})),n.d(t,"h",(function(){return f})),n.d(t,"g",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"c",(function(){return m})),n.d(t,"d",(function(){return g})),n.d(t,"e",(function(){return y})),n.d(t,"i",(function(){return v})),n.d(t,"a",(function(){return I})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return j}));var r=n(11);const u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],o=["January","February","March","April","May","June","July","August","September","October","November","December"],c=o.map(e=>e.toLowerCase());function d(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function a(e){return d(e).getTime()}function i(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function s(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function f(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function l(e){const t="number"==typeof e?new Date(e):e,n=d(new Date);if(t>=n)return f(t);const o=new Date(n);if(o.setDate(n.getDate()-7),t>=o)return Object(r.b)("Weekday.Short"+u[t.getDay()]);const c=t.getFullYear()!==n.getFullYear();return p(t,Object(r.b)(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM"))}function b(e){return p("number"==typeof e?new Date(e):e,Object(r.b)("formatterYearMax")||"dd.MM.yyyy")}function h(e,t=!1){return p(e,Object(r.b)(t?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy")}function m(e,t=!1,n=!1){const o="number"==typeof e?new Date(e):e,c=d(new Date);if(!n){if(s(o)===s(c))return(t?C:E)(Object(r.b)("Weekday.Today"));const e=new Date(c);if(e.setDate(c.getDate()-1),s(o)===s(e))return(t?C:E)(Object(r.b)("Weekday.Yesterday"));const n=new Date(c),d=new Date(c);if(n.setDate(c.getDate()-7),d.setDate(c.getDate()+7),o>=n&&o<=d){const e=u[o.getDay()];return t?C(Object(r.b)("Weekday.Short"+e)):E(Object(r.b)("Weekday."+e))}}const a=o.getFullYear()!==c.getFullYear(),i=t?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate";return(t?C:E)(p(o,Object(r.b)(i)||"d MMMM yyyy"))}function p(e,t){const n=e.getDate(),u=e.getMonth();return t.replace("LLLL",Object(r.b)(o[u])).replace("MMMM",Object(r.b)("Month.Gen"+o[u])).replace("MMM",Object(r.b)("Month.Short"+o[u])).replace("MM",String(u+1).padStart(2,"0")).replace("dd",String(n).padStart(2,"0")).replace("d",String(n)).replace("yyyy",String(e.getFullYear()))}function g(e){const t="number"==typeof e?new Date(e):e;return`${m(t,!0)}, ${f(t)}`}function y(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function v(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const u=(e=Math.floor(e/60))%60;e-=u;const o=(e=Math.floor(e/60))%60;return o>0&&t.push(String(o).padStart(2,"0")),t.push(String(u).padStart(o>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function I(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],d=(t?u[1]:u[0]).toLowerCase(),a=c.findIndex(e=>e.startsWith(d));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function j(e){return e+86400}function C(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function E(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"a",(function(){return l}));var r=n(10),u=n(1),o=n(2),c=n(7);function d(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function a(){return!!c.j&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(u.o&&console.log("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(u.o&&console.log("[PUSH] Push messaging isn't supported."),!1):(u.o&&console.log("[PUSH] Push notifications aren't supported."),!1))}async function i(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=d(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){u.o&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function s(){if(!a())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await i(t)}async function f(){if(!a())return;const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(d(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await i(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=d(t);u.o&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?u.o&&console.log("[PUSH] Permission for Notifications was denied"):u.o&&console.log("[PUSH] Unable to subscribe to push.",e)}}}function l(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#21212140"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";var r=n(0),u=n(8);n(85);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:d,download:a,disabled:i,destructive:s,ariaLabel:f}=e,l=Object(r.m)(e=>{if(i||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[i,c]),b=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return i||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[i,c]),h=Object(u.a)("MenuItem",n,i&&"disabled",s&&"destructive"),m=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t}),o);return d?r.a.createElement("a",{tabIndex:0,className:h,href:d,download:a,"aria-label":f,title:f,target:"_blank",rel:"noopener noreferrer"},m):r.a.createElement("div",{role:"button",tabIndex:0,className:h,onClick:l,onKeyDown:b,"aria-label":f,title:f},m)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(79);t.a=()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),o=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,o=u.getBoundingClientRect(),c=u.offsetWidth/2;t([...e,{x:r.clientX-o.x-c/2,y:r.clientY-o.y-c/2,size:c}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:o},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(73),u=n.n(r),o=n(7),c=n(14),d=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(d.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(o.o)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(c.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(c.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),o=n(1),c=n(7),d=n(67),a=n(8),i=n(68),s=n(51);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return o=e,c=n.highlight,o.reduce((e,t)=>{if("string"!=typeof t||!c)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(c.toLowerCase()),o=n[u+c.length];if(u<0||o&&o.match(f))return[...e,t];const d=[];return d.push(t.substring(0,u)),d.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+c.length))),d.push(t.substring(u+c.length)),[...e,...d]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let o=n.shift(),c=0;for(;o;){const e=t.indexOf(o,c);u.push(t.substring(c,e)),o.startsWith("@")?u.push(r.a.createElement(i.a,{username:o},o)):u.push(r.a.createElement(s.a,{text:o,url:o})),c=e+o.length,o=n.shift()}return u.push(t.substring(c)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var o,c;return e},[e])}function h(e,t,n){return c.c?e:e.reduce((e,o)=>{if("string"!=typeof o)return[...e,o];const c=o.split(u.a),i=o.match(u.a)||[];return e.push(c[0]),i.reduce((e,o,i)=>{const s=Object(d.a)(Object(u.b)(o)),f=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(r.a.createElement("img",{className:f,src:`./img-apple-${"big"===t?"160":"64"}/${s}.png`,alt:o})),"html"===n&&e.push(`${o}`);const l=2*i+2;return c[l]&&e.push(c[l]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,o)=>{const c=n.trimLeft(),d=n.length-c.length;return e.push(String.fromCharCode(160).repeat(d)+c),u!==o.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(o.fb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),o=n.match(l)||[];return e.push(u[0]),o.reduce((e,n,o)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const c=2*o+2;return u[c]&&e.push(u[c]),e},e)},[])}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"q",(function(){return o})),n.d(t,"G",(function(){return c})),n.d(t,"r",(function(){return d})),n.d(t,"F",(function(){return a})),n.d(t,"K",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"I",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"L",(function(){return m})),n.d(t,"v",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return I})),n.d(t,"J",(function(){return w})),n.d(t,"cb",(function(){return O})),n.d(t,"i",(function(){return j})),n.d(t,"j",(function(){return C})),n.d(t,"T",(function(){return E})),n.d(t,"bb",(function(){return S})),n.d(t,"f",(function(){return A})),n.d(t,"x",(function(){return k})),n.d(t,"ib",(function(){return T})),n.d(t,"jb",(function(){return P})),n.d(t,"t",(function(){return N})),n.d(t,"N",(function(){return D})),n.d(t,"M",(function(){return L})),n.d(t,"l",(function(){return F})),n.d(t,"E",(function(){return B})),n.d(t,"m",(function(){return R})),n.d(t,"gb",(function(){return x})),n.d(t,"fb",(function(){return U})),n.d(t,"O",(function(){return _})),n.d(t,"p",(function(){return G})),n.d(t,"hb",(function(){return $})),n.d(t,"n",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"lb",(function(){return K})),n.d(t,"mb",(function(){return V})),n.d(t,"e",(function(){return q})),n.d(t,"db",(function(){return Y})),n.d(t,"k",(function(){return J})),n.d(t,"P",(function(){return Z})),n.d(t,"Q",(function(){return X})),n.d(t,"S",(function(){return ee})),n.d(t,"R",(function(){return te})),n.d(t,"W",(function(){return ue})),n.d(t,"s",(function(){return oe})),n.d(t,"X",(function(){return ce})),n.d(t,"V",(function(){return ae})),n.d(t,"U",(function(){return ie})),n.d(t,"Z",(function(){return fe})),n.d(t,"Y",(function(){return le})),n.d(t,"u",(function(){return be})),n.d(t,"ab",(function(){return he})),n.d(t,"a",(function(){return me})),n.d(t,"o",(function(){return pe})),n.d(t,"kb",(function(){return ge})),n.d(t,"eb",(function(){return ye})),n.d(t,"C",(function(){return ve})),n.d(t,"A",(function(){return Ie})),n.d(t,"y",(function(){return we})),n.d(t,"D",(function(){return Oe})),n.d(t,"z",(function(){return je})),n.d(t,"B",(function(){return Ce})),n.d(t,"g",(function(){return Ee})),n.d(t,"h",(function(){return Se}));var r=n(1),u=n(3);function o(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function c(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:o(e,t,[...r||[],...u])}function d(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:o}=e.chats,c=o[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...c.photos||[]]}};return i.id&&i.type?d(e,{...o,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.g?"archived":"active";let o=e.chats.listIds;return Object.keys(o).forEach(e=>{const n=o[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(o={...o,[e]:n.filter(e=>e!==t)}):o={...o,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:o}},t,{folderId:n||void 0})}function l(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}var b=n(4),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(e,t){const n=t.reduce((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e),{});return Object.keys(n).map(Number).forEach(t=>{e=I(e,t,n[t])}),e}function I(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function w(e,t,n,r){const u=Object(h.m)(e,t)||{},o={...u[n],...r};return o.id?p(e,t,{...u,[n]:o}):e}function O(e,t,n,r){const u=Object(h.nb)(e,t)||{},o={...u[n],...r};return o.id?N(e,t,{...u,[n]:o},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const o=Object(u.j)(r,n),c=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.X)(e,t,r),o=Object(h.db)(e,t,r),c=Object(h.Eb)(e,t,r),d=Object(h.gb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",o),e=y(e,t,r,"viewportIds",c),e=y(e,t,r,"pinnedIds",d)}),c.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;c.forEach(n=>{const{fromChatId:o,fromMessageId:c}=n.forwardInfo,d=Object(h.k)(e,o,c);r&&u===c&&(e=m(e,t)),d&&(e=w(e,o,c,{threadInfo:void 0}))})}return e=p(e,t,o)}function C(e,t,n){const r=Object(h.nb)(e,t);if(!r)return e;const o=Object(u.j)(r,n);let c=Object(h.lb)(e,t);return c&&(n.forEach(e=>{c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",c)),e=N(e,t,o,void 0)}function E(e,t,n,r){const u=Object(h.X)(e,t,n),o=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!o.length?e:y(e,t,n,"listedIds",M([...u||[],...o]))}function S(e,t,n,r){const u=Object(h.db)(e,t,n),o=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!o.length?e:y(e,t,n,"outlyingIds",M([...u||[],...o]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const o=Object(h.Eb)(e,t,n)||[];if(o.includes(u))return e;return y(e,t,n,"viewportIds",M([...o.length{e=T(e,t.chatId,t.threadId,t)}),e}function N(e,t,n,r){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function L(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function F(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,o,c,d,a=!1){const{selectedMessages:i}=e;c&&(d=Object(h.Z)(e,t,c));const s=d||[o];if(!i)return F(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const c=Object(h.x)(e,t,n,r),d=c.indexOf(f[f.length-1]),a=c.indexOf(o),i=Math.min(d,a),s=Math.max(d,a),b=c.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:R(e)}function R(e){return{...e,selectedMessages:void 0}}function x(e,t,n,r,o){const c=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(c,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let o;if(t||!u)o=n;else{const e=new Set(u.map(e=>e.id));o=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:o}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const o=[...Object(h.vb)(e,t),...n||[]],c=Object(u.o)(o.map(({id:e})=>e)),d=Object(u.c)(o,"id"),a=c.map(e=>d[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var z=n(45);function H(e,t){return{...e,users:{...e.users,byId:t}}}function K(e,t,n){const{byId:r}=e.users,{hash:o,userIds:c}=e.contactList||{},d=r[t],a=n.isMin&&d&&!d.isMin,i={...d,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&c&&!c.includes(t)&&(e={...e,contactList:{hash:o||0,userIds:[t,...c]}}),H(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=K(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=K(e,r,t[r]))}),e}function Y(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function J(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],H(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):z.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,o){const{resultsByType:c}=e.globalSearch||{},d=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=c&&c[r]?c[r].foundIds:void 0;if(void 0!==a&&Object.keys(d).every(e=>a.includes(Q(d[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(5);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],isActive:r,query:u})}function oe(e,t,n,r,u,o){const c=Object(ne.a)(t,n);return re(e,c,{...e.localTextSearch.byChatThreadKey[c],results:{foundIds:r,totalCount:u,nextOffsetId:o}})}function ce(e,t,n,r,o,c){const d=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[d]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return oe(e,t,n,Object(u.a)(i,s)?i:s,o,c)}function de(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return de(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,o,c){const{resultsByType:d}=e.localMediaSearch.byChatId[t]||{},a=d&&d[n]?d[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,o){return de(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:o}}})}(e,t,n,Object(u.a)(a,i)?a:i,o,c)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function me(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function pe(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ge(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function ye(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function ve(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function we(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:o}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:o}}}}function Oe(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function je(e,t){return{...e,payment:{...e.payment,...t}}}function Ce(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:o,title:c}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:o,title:c}}}}function Ee(e){return{...e,payment:{}}}function Se(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:d,success:a,disabled:i,readOnly:s,placeholder:f,autoComplete:l,inputMode:b,maxLength:h,onChange:m,onInput:p,onKeyPress:g,onKeyDown:y,onBlur:v})=>{const I=d||a||c,w=Object(u.a)("input-group",o&&"touched",d?"error":a&&"success",i&&"disabled",s&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:w},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,value:o||"",placeholder:f,maxLength:h,autoComplete:l,inputMode:b,disabled:i,readOnly:s,onChange:m,onInput:p,onKeyPress:g,onKeyDown:y,onBlur:v}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),o=n(20);n(81);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:d,checked:a,disabled:i,round:s,blocking:f,isLoading:l,onChange:b,onCheck:h})=>{const m=Object(r.m)(e=>{b&&b(e),h&&h(e.currentTarget.checked)},[b,h]),p=Object(u.a)("Checkbox",i&&"disabled",s&&"round",l&&"loading",f&&"blocking");return r.a.createElement("label",{className:p},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:a,disabled:i,onChange:m}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label"},c),d&&r.a.createElement("span",{className:"subLabel"},d)),l&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(50);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c}));var r=n(0);let u,o=!1;const c=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),o=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{o=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(o&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function o(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function c(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return c}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(29),o=n(69),c=n(52),d=n(42),a=n(8),i=n(43);n(83);t.a=({ref:e,containerRef:t,isOpen:n,className:s,style:f,children:l,positionX:b="left",positionY:h="top",autoClose:m=!1,footer:p,noCloseOnBackdrop:g=!1,onCloseAnimationEnd:y,onClose:v,onMouseEnter:I,onMouseLeave:w})=>{let O=Object(r.q)(null);e&&(O=e);const j=t||O,{transitionClassNames:C}=Object(u.a)(n,y);Object(r.n)(()=>n&&v?Object(d.a)(v):void 0,[n,v]),Object(c.a)(([e])=>{void 0!==e&&Object(i.b)(200)},[n]);const E=((e,t,n)=>{const[u,o]=Object(r.r)(-1);Object(r.n)(()=>{o(-1)},[t]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n();if(38!==t.keyCode&&40!==t.keyCode)return;const c=document.activeElement,d=Array.from(r.children);let a=c&&d.indexOf(c)||u;if(38===t.keyCode&&a>0)a--;else if(40===t.keyCode&&a{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(36);const m={[r.ApiMediaFormat.DataUri]:c.a.Text,[r.ApiMediaFormat.BlobUrl]:c.a.Blob,[r.ApiMediaFormat.Lottie]:c.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.h?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.L){const n=e.startsWith("avatar")?u.N:u.M,r=await c.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.g||(t=await b(t)),"image/webp"===r.type&&!Object(a.o)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=w(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let c=!1;return r.addEventListener("sourceopen",()=>{if(c)return;c=!0;const u=r.addSourceBuffer("audio/mpeg");Object(o.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(o.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.g){const e=await Object(d.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=w(t),f=e.type}if("image/webp"===f&&!Object(a.o)()){const t=await Object(d.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=w(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.o&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function I(e){Object(o.b)(e)}function w(e){return e instanceof Blob?URL.createObjectURL(e):e}a.h&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const c=await Object(o.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!c)return;const{arrayBuffer:d,mimeType:a,fullSize:i}=c;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:d,mimeType:a,fullSize:i}},[d])})},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(9);let u=o();function o(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}const c=Object(r.g)(()=>{u=o()},250,!0);window.addEventListener("resize",c),window.addEventListener("orientationchange",c),t.a={get:()=>u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onTab:[]};function o(e){return c()||document.addEventListener("keydown",d,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),c()||document.removeEventListener("keydown",d,!1)}(e)}}function c(){return Object.values(u).some(e=>Boolean(e.length))}function d(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";var r=n(0),u=n(2);const o=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function c(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function d(e,t){const n=[],r=[],u=e.length;let d,a,i,s,f,l,b,h,m,p,g,y,v;for(d=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(I=e.charCodeAt(b++))-48<10?I-22:I-65<26?I-65:I-97<26?I-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=c(i-h,a,0===h),Math.floor(i/a)>2147483647-d)throw RangeError("punycode_overflow(3)");d+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,d),i++}var I;if(t)for(i=0,v=n.length;iObject(s.l)(t,["openTelegramLink"]))(({url:e,text:t,className:n,children:u,openTelegramLink:o})=>{const c=Object(r.m)(t=>!(!(t.ctrlKey||t.altKey||t.shiftKey||t.metaKey)&&e&&(e.match(i.hb)||e.match(i.gb)))||(t.preventDefault(),o({url:e}),!1),[o,e]);if(!e)return;const d=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:d,onClick:c},u||t)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return o})),n.d(t,"a",(function(){return c})),n.d(t,"c",(function(){return d}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(e){const{fileName:t,mimeType:n}=e;return o(t,n)}function o(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function c(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function d(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return c}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:o,fieldError:c,description:d}=u?r[u]:r[n];return{field:o,fieldError:c,description:d||t}}const o={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function c(e){return Object.values(e).reduce((e,t)=>{const n=o[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return c}));var r=n(9);let u;function o(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&o(e,t)})}function c(e){Object(r.b)(()=>{e()&&c(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(47);n(84);t.a=({trigger:e,className:t,children:n,positionX:o="left",positionY:c="top",footer:d})=>{const a=Object(r.q)(null),i=Object(r.q)(null),[s,f]=Object(r.r)(!1);return r.a.createElement("div",{ref:i,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=a.current;if(!s||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{f(!s)},isOpen:s}),r.a.createElement(u.a,{ref:a,containerRef:i,isOpen:s,className:t||"",positionX:o,positionY:c,footer:d,autoClose:!0,onClose:()=>{f(!1)}},n))}},function(e,t,n){"use strict";var r=n(0),u=n(22),o=n(1),c=n(27);const d=new Set(["key","ref","teactFastList","teactOrderKey"]),a={autoPlay:"autoplay",autoComplete:"autocomplete"},i={};function s(e,t,n,u,c,{skipComponentUpdate:d=!1,forceIndex:a=!1,fragment:i,moveDirection:g}={}){if(!d&&t&&n&&Object(r.d)(t)&&Object(r.d)(n)&&!Object(r.c)(t,n)&&(n=function(e,t){return e.componentInstance.props=t.componentInstance.props,Object(r.j)(e.componentInstance)}(t,n)),!d&&n&&Object(r.d)(n)&&n.componentInstance.isMounted&&l(n,u,c,e),t===n)return n;if(!t&&n){Object(r.d)(n)&&(n=f(n,u,c,e));const t=b(n);Object(r.k)(n,t),a&&e.childNodes[c]?e.insertBefore(t,e.childNodes[c]):(i||e).appendChild(t)}else if(t&&!n)e.removeChild(Object(r.b)(t)),Object(r.l)(t);else if(t&&n)if(Object(r.c)(t,n)){Object(r.d)(n)&&(n=f(n,u,c,e));const o=b(n);Object(r.k)(n,o),e.replaceChild(o,Object(r.b)(t)),Object(r.l)(t)}else{const u=Object(r.d)(t)&&Object(r.d)(n);if(u||Object(r.k)(n,Object(r.b)(t)),Object(r.f)(t)&&Object(r.f)(n)){if(g){const n=Object(r.b)(t),u=e.childNodes["up"===g?c:c+1];u?e.insertBefore(n,u):(i||e).appendChild(n)}u||function(e,t,n){const r=Object.keys(e.props),u=Object.keys(t.props);r.forEach(r=>{void 0!==e.props[r]&&void 0===t.props[r]&&p(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?m(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(p(e,t,n),m(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return o.o&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let c=0;const d=e.children.reduce((e,r,o)=>{let d="props"in r?r.props.key:void 0;if(d&&!u.has(d))return s(n,r,void 0,t,-1),e;if(!d){const u=t.children[o],c=u&&"props"in u?u.props.key:void 0;if(!u||c)return s(n,r,void 0,t,-1),e;d="__indexKey#"+o}return e[d]={$element:r,index:c++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,f=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,o=d[u];if(!o)return a||(a=[],i=r),void a.push(e);a&&(f=f.concat(h(a,i,n,t)),i=void 0,a=void 0);const c="props"in e?e.props.teactOrderKey:void 0,b=o.index!==l&&o.order!==c,m=b&&l>o.index;b&&!m||l++,f.push(s(n,o.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:m?"down":"up"}}))}),a&&(f=f.concat(h(a,i,n,t)));return f}(e,t,n);const u=Math.max(e.children.length,t.children.length),c=[],d=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:d}:void 0);u&&c.push(u)}d&&n.appendChild(d);return c}(t,n,u?e:Object(r.b)(t))}}return n}function f(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:o}=e;if(!o.isMounted){l(e=Object(r.i)(o),t,n,u);const c=e.children[0];Object(r.d)(c)&&(e.children=[f(c,e,0,u)]),o.isMounted=!0}return e}function l(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=s(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function b(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return b(e.children[0]);const{tag:t,props:n,children:u=[]}=e,o=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=o),Object.keys(n).forEach(e=>{m(o,e,n[e])}),e.children=u.map((t,n)=>s(o,void 0,t,e,n)),o}function h(e,t,n,r){if(1===e.length)return[s(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),o=e.map(e=>s(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),o}throw new Error("Unexpected input")}function m(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(c.a)(e,t,n):t.startsWith("data-")?e.setAttribute(t,n):d.has(t)||(e[a[t]||t]=n))}function p(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(c.c)(e,t,n):t.startsWith("data-")?e.removeAttribute(t):d.has(t)||delete e[a[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(i),i[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=i[n];r.children=[s(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";var r=n(15);const u=new RegExp(`^(?:${r.a.source})+$`,"");t.a=e=>{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return o})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,o="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(55),u=n(33);let o=!1;const c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,d=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=c.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const o=Math.round(d(u[e].r,u[t].r,n)),c=Math.round(d(u[e].g,u[t].g,n)),a=Math.round(d(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(d(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${o},${c},${a},${i/255})`:`rgb(${o},${c},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=o&&t,c=n?0:1,d=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),o&&document.documentElement.classList.add("disable-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("disable-animations")},500),o=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(c,d,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(c,d)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function o(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map(e=>e.toString(16).padStart(4,"0")).join("-")}return t}function c(e){const t={categories:[],emojis:{}};for(let n=0;n({userOrChat:t?Object(c.Db)(e,t):void 0}),(e,t)=>Object(o.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:o})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&o({username:e.substring(1)})},className:"text-entity-link"},n))},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"e1066b23c5448d0199e4.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),o=n(11),c=n(66);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:d}=e.settings.byKey;Object(o.c)(d),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.k?"is-touch-env":"is-pointer-env"),Object(c.a)(t,n>0),u.i&&document.body.classList.add("is-safari"),u.d?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0}))},function(e,t,n){"use strict";var r=n(2),u=n(1),o=n(10),c=n(32),d=n(13);Object(r.b)("initApi",(e,t)=>{const n=localStorage.getItem(u.C)||void 0;return Object(o.c)(t.apiUpdate,n),{...e,authIsSessionRemembered:Boolean(n)}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(o.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(o.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(o.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(o.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(o.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(o.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(o.a)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{const{sessionId:r}=n;localStorage.setItem(u.C,r)}),Object(r.b)("signOut",()=>{(async()=>{await Object(c.c)(),await Object(o.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{localStorage.removeItem(u.C),d.b(u.M),d.b(u.N),d.b(u.O),d.b(u.l),d.b(u.F),Object(r.d)().init()}),Object(r.b)("disconnect",()=>{(async()=>{await Object(o.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(o.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t,n){"use strict";var r=n(2),u=n(1),o=n(32),c=n(39),d=n(11);Object(r.b)("apiUpdate",(e,t,n)=>{switch(u.o&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(o.b)(),Object(d.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":{if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()});const{sessionId:u}=e;u&&t.authRememberMe&&Object(r.d)().saveSession({sessionId:u});break}}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(c.lb)(Object(r.e)(),t.id,t),currentUserId:t.id})}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(21),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),o=n(2),c=n(7);function d(e){const t=e.data;if(u.o&&console.log("[SW] New action from service worker",t),!t.type)return;const n=Object(o.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}c.j&&window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.o&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.o&&console.log("[SW] ServiceWorker ready"),navigator.serviceWorker.addEventListener("message",d)):(u.o&&console.error("[SW] ServiceWorker not available"),Object(o.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.o&&console.error("[SW] ServiceWorker registration failed: ",e)}});var a=n(57);const i={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{}},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.r,isBackgroundBlurred:!0,patternColor:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},privacy:{}},twoFaSettings:{}};var s=n(4),f=n(9),l=n(3),b=n(6);const h=Object(f.g)((function(){Object(f.c)(()=>{if(!m)return;const e=Object(o.e)();if(e.isLoggingOut)return;const t={...i,...Object(l.l)(e,["authState","authPhoneNumber","authRememberMe","authIsSessionRemembered","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","push"]),isChatInfoShown:g(e),users:y(e),chats:v(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:w(e)},n=JSON.stringify(t);localStorage.setItem(u.A,n)})}),1e3,!1);let m=!1;function p(e){if(!u.z){if(localStorage.getItem(u.C))return m=!0,Object(o.a)(h),function(e){u.o&&console.time("global-state-cache-read");const t=localStorage.getItem(u.A),n=t?JSON.parse(t):void 0;u.o&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey});return{...e,...n}}(e);m=!1}}function g(e){return window.innerWidth>u.Z&&e.isChatInfoShown}function y(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.y).filter(e=>e>0),...Object.keys(t)].slice(0,u.B);return{byId:Object(l.l)(t,r),selectedId:window.innerWidth>u.Z?n:void 0}}function v(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.y)],{chatId:n}=Object(b.y)(e)||{};return{...e.chats,byId:Object(l.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(b.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.y),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[s.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(l.l)(r.byId,u.viewportIds),threadsById:{[s.MAIN_THREAD_ID]:u}})});const r=Object(b.y)(e);return{byChatId:t,messageLists:!r||c.f?void 0:[{...r,threadId:s.MAIN_THREAD_ID,type:"thread"}]}}function w(e){const{byKey:t}=e.settings;return{byKey:t,privacy:{}}}u.z||(Object(o.b)("saveSession",()=>{m=!0,Object(o.a)(h)}),Object(o.b)("reset",()=>{m=!1,Object(o.f)(h),localStorage.removeItem(u.A)})),Object(o.b)("init",()=>{const e=Object(l.d)(i),t=p(e)||e,n=Object(b.y)(t)||{};return window.history.replaceState(n,""),t});var O=n(0),j=n(49);const C=String(Date.now()+Math.random());let E;localStorage.setItem("tt-active-tab",C);const S=window.setInterval(()=>{E&&localStorage.getItem("tt-active-tab")!==C&&(E(),clearInterval(S))},2e3);var M=n(28),A=(n(74),n(75),n(76),n(24)),k=n(29),T=n(14);const P=["400 1em Roboto","500 1em Roboto"];function N(){if("fonts"in document)return Promise.all(P.map(e=>document.fonts.load(e)))}var D=n(48),L=n(12),F=n(8),B=(n(77),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),R=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function x(){const{listIds:e,byId:t}=Object(o.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(A.d)(n);return r?D.b(r,s.ApiMediaFormat.DataUri):void 0}))}const U={main:()=>Promise.all([Object(L.d)(L.a.Main,"Main").then(N),x()]),authPhoneNumber:()=>Promise.all([N(),Object(T.g)(B)]),authCode:()=>Object(T.g)(R),authPassword:()=>Object(T.g)(R),authQrCode:N};var _=Object(o.h)(e=>({uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(e.settings.byKey.customBackground),isCustomBackgroundColor:Boolean((e.settings.byKey.customBackground||"").match(/^#[a-f\d]{6,8}$/i)),isRightColumnShown:Object(b.V)(e)}),(e,t)=>Object(l.l)(t,["setIsUiReady"]))(({page:e,children:t,hasCustomBackground:n,isCustomBackgroundColor:r,isRightColumnShown:u,setIsUiReady:o})=>{const[c,d]=Object(M.a)(),{shouldRender:a,transitionClassNames:i}=Object(k.a)(!c,void 0,!0);return Object(O.n)(()=>{let t;return Promise.race([Object(f.e)(700),U[e]()]).then(()=>{d(),o({uiReadyState:1}),t=window.setTimeout(()=>{o({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),o({uiReadyState:0})}},[]),O.a.createElement("div",{id:"UiLoader"},t,a&&O.a.createElement("div",{className:Object(F.a)("mask",i)},"main"===e?O.a.createElement(O.a.Fragment,null,O.a.createElement("div",{className:"left"}),O.a.createElement("div",{className:Object(F.a)("middle",n&&!r&&"custom-bg-image",n&&r&&"custom-bg-color",u&&"with-right-column")}),u&&O.a.createElement("div",{className:"right"})):O.a.createElement("div",{className:"blank"})))}),G=n(18),$=n(25),W=n(41),z=n(40),H=n(16),K=n(46),V=n(37),q=n(56),Y=n(34),J=n(20);n(86);const Q=200+u.c;var Z=Object(O.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(O.q)(null),[o,c]=Object(O.r)(),[d,a]=Object(O.r)(G.a);function i(e){c(e),a(function(e=""){return e.length?G.a.filter(t=>Object(K.a)(t.name,e)):G.a}(e))}const s=Object(O.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=G.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),Q)},[r]),f=Object(O.m)(e=>{i(e.currentTarget.value)},[]),l=Object(O.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===o&&(n.value=""),i(n.value)},[o,t]);return O.a.createElement(q.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:c})=>{const d=()=>{if(c)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==o?o:t&&t.name||"";return O.a.createElement("div",{className:Object(F.a)("input-group",t&&"touched")},O.a.createElement("input",{ref:u,className:Object(F.a)("form-control",c&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:d,onFocus:d,onInput:f,onKeyDown:l}),O.a.createElement("label",null,"Country"),n?O.a.createElement(J.a,{color:"black"}):O.a.createElement("i",{onClick:d,className:Object(F.a)("css-icon-down",c&&"open")}))}},d.map(e=>O.a.createElement(Y.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},O.a.createElement("span",{"data-country-id":e.id}),O.a.createElement("span",{className:"country-flag"},Object(V.a)(e.flag,["hq_emoji"])),O.a.createElement("span",{className:"country-name"},e.name),O.a.createElement("span",{className:"country-code"},e.code))),!d.length&&O.a.createElement(Y.a,{key:"no-results",className:"no-results",disabled:!0},O.a.createElement("span",null,"No countries matched your filter.")))});let X=!1;var ee=Object(O.h)(Object(o.h)(e=>Object(l.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(l.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:o,authRememberMe:d,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(O.q)(null),[m,p]=Object(O.r)(),[g,y]=Object(O.r)(),[v,I]=Object(O.r)(!1),[w,j]=Object(O.r)(),C=m?`${m.code} ${g||""}`:g,E=C&&C.replace(/[^\d]+/g,"").length>=10;Object(O.n)(()=>{c.k||h.current.focus()},[m]),Object(O.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(O.n)(()=>{!a||m||v||p(Object(G.d)(a))},[m,a,v]);const S=Object(O.m)(e=>{const t=Object(G.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(G.b)(e,n))},[m]);Object(O.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(O.o)(()=>{h.current&&w&&h.current.setSelectionRange(...w)},[w]);const M=Object(O.m)(e=>{o&&l(),X||(X=!0,N(),Object(T.g)(R));const{value:t,selectionStart:n,selectionEnd:r}=e.target;j(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return O.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},O.a.createElement("div",{className:"auth-form"},O.a.createElement("div",{id:"logo"}),O.a.createElement("h2",null,"Sign in to Telegram"),O.a.createElement("p",{className:"note"},"Please confirm your country and",O.a.createElement("br",null),"enter your phone number."),O.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:C})}},O.a.createElement(Z,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),O.a.createElement(z.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:C,error:o,inputMode:"tel",onChange:M}),O.a.createElement(W.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(d),onChange:A}),E&&(k?O.a.createElement($.a,{type:"submit",ripple:!0,isLoading:r},"Next"):O.a.createElement(H.a,null)),k&&O.a.createElement($.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),te=n(17);var ne=()=>{const e=Object(te.a)(L.a.Auth,"AuthCode");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var re=()=>{const e=Object(te.a)(L.a.Auth,"AuthPassword");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var ue=()=>{const e=Object(te.a)(L.a.Auth,"AuthRegister");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};var oe=()=>{const e=Object(te.a)(L.a.Auth,"AuthQrCode");return e?O.a.createElement(e,null):O.a.createElement(H.a,null)};n(87);var ce=Object(O.h)(Object(o.h)(e=>Object(l.l)(e,["authState"]),(e,t)=>Object(l.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(O.n)(()=>{t(),n()},[t,n]),Object(O.n)(()=>{},[]),e){case"authorizationStateWaitCode":return O.a.createElement(_,{page:"authCode",key:"authCode"},O.a.createElement(ne,null));case"authorizationStateWaitPassword":return O.a.createElement(_,{page:"authPassword",key:"authPassword"},O.a.createElement(re,null));case"authorizationStateWaitRegistration":return O.a.createElement(ue,null);case"authorizationStateWaitQrCode":return O.a.createElement(_,{page:"authQrCode",key:"authQrCode"},O.a.createElement(oe,null));case"authorizationStateWaitPhoneNumber":default:return O.a.createElement(_,{page:"authPhoneNumber",key:"authPhoneNumber"},O.a.createElement(ee,null))}}));var de=()=>{const e=Object(te.a)(L.a.Main,"Main");return e?O.a.createElement(e,null):void 0},ae=n.p+"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png";n(88);var ie=()=>O.a.createElement("div",{id:"AppInactive"},O.a.createElement("div",{className:"content"},O.a.createElement("img",{src:ae,alt:""}),O.a.createElement("h3",{className:"title"},"Such error, many tabs"),O.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",O.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),O.a.createElement("div",{className:"actions"},O.a.createElement($.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function se(){return o.c.createElement(_,{page:"main",key:"main"},o.c.createElement(de,null))}var fe=Object(o.h)(e=>Object(l.l)(e,["authState","authIsSessionRemembered"]),(e,t)=>Object(l.l)(t,["disconnect"]))(({authState:e,authIsSessionRemembered:t,disconnect:n})=>{const[r,c]=Object(M.a)(!1);if(Object(O.n)(()=>{Object(j.b)(),E=()=>{n(),document.title=`${u.db}${u.D}`,c()}},[n,c]),r)return o.c.createElement(ie,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return o.c.createElement(ce,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return se()}return t?se():o.c.createElement(ce,null)});n(89);u.o&&console.log(">>> INIT"),Object(o.d)().init(),u.o&&console.log(">>> START INITIAL RENDER"),a.a.render(o.c.createElement(fe,null),document.getElementById("root")),u.o&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(o.e)())})}]); +//# sourceMappingURL=main.c83b96912904b35c9d32.js.map \ No newline at end of file diff --git a/dist/main.c7769ee2bb8655152f13.js.map b/dist/main.c83b96912904b35c9d32.js.map similarity index 99% rename from dist/main.c7769ee2bb8655152f13.js.map rename to dist/main.c83b96912904b35c9d32.js.map index 1927623f..c201a22e 100644 --- a/dist/main.c7769ee2bb8655152f13.js.map +++ b/dist/main.c83b96912904b35c9d32.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/util/iteratees.ts","webpack:///./src/api/types/index.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/util/generateIdFor.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/util/pushNotifications.ts","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/util/switchTheme.ts","webpack:///./src/util/emoji.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./src/components/auth/AuthQrCode.async.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","1","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","getTarget","setTarget","useState","initial","newValue","scheduleNextState","throttleWithPrimaryRaf","applyNextState","throttleWithRaf","currentElement","forceUpdateComponent","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","propsRef","renderedRef","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_INFO","process","IS_TEST","DEBUG_ALERT_MSG","GRAMJS_SESSION_ID_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","isBigScreen","Set","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","STICKER_SIZE_INLINE_DESKTOP_FACTOR","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","LAYERS_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","getUnequalProps","join","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacksThrottled","cb","newGlobal","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","id","generateIdFor","useForceUpdate","delete","set","currentProps","newProps","currentKeys","filter","prop","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","caption","title","performer","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","isMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","replace","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","selectFirstUnreadId","outlyingIds","lastReadId","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","settings","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","DPR","devicePixelRatio","MASK_IMAGE_ENABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","throttleWithTickEnd","waiting","onIdle","requestIdleCallback","pause","rafPromise","requestAnimationFrame","fastRafCallbacks","isPrimary","unshift","currentCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionId","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","cache","langPack","runCallbacks","createCallbackManager","currentLangCode","async","setLanguage","langCode","lang","newLangPack","cached","cacheApi","Json","remote","sourceLangPacks","fetchFromCacheOrRemote","fetch","pairs","json","extraLangPack","clear","getTranslation","format","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","Bundles","LOAD_PROMISES","MEMORY_CACHE","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","caches","Type","cacheName","Request","open","Blob","blob","substr","headers","save","cacheData","JSON","stringify","Response","put","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","getContext","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","localStorage","getItem","removeItem","location","reload","APP_ENV","store","random","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","isNotJoined","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","privateChatUser","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","filters","pinnedIds","getFolderChatsCount","isChat","chatOrUser","getMessageSenderName","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onClick","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleClick","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","body","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasAsyncOpenClassName","setHasAsyncOpenClassName","hasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","formatKey","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","setTrigger","trigger","getDeviceToken","subscription","toJSON","endpoint","checkIfSupported","ServiceWorkerRegistration","Notification","permission","unsubscribe","dispatch","deviceToken","deleteDeviceToken","unsubscribeFromPush","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribeToPush","subscribedAt","checkIfShouldResubscribe","subscribe","userVisibleOnly","setDeviceToken","notifyClientReady","controller","MenuItem","icon","destructive","handleKeyDown","keyCode","role","onKeyDown","RippleEffect","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","RE_MENTION","nextLink","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","usePrevious","next","shouldSkipUndefined","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","hash","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","replaceSettings","newSettings","updateNotifySettings","peerType","isSilent","isShowPreviews","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","onSelectWithEnter","focusedIndex","setFocusedIndex","focusedElement","activeElement","elementChildren","newIndex","focus","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","windowSize","updateSizes","vh","setProperty","handleResize","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","utf16","len","RangeError","adapt","delta","numpoints","firsttime","k","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","getHref","getDecodedUrl","decodedHref","decodeURI","convertPunycode","openTelegramLink","ctrlKey","altKey","shiftKey","metaKey","classNames","prevDeps","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","dropdownRef","setIsOpen","menu","onTrigger","FILTERED_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","MESSAGE_DELETED","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","parseInt","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","theme","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","fromCodePoint","toString","uncompressEmoji","emojiData","categories","emojiRaw","colons","native","image","openChat","openChatByUsername","contains","animationLevel","messageTextSize","language","switchTheme","uiReadyState","authPhoneNumber","authRememberMe","authError","apiUpdate","authIsSessionRemembered","authIsLoading","password","file","authIsLoadingQrCode","setItem","reset","init","connectionState","authNearestCountry","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","saveSession","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","currentUser","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","focusMessage","register","INITIAL_STATE","isLeftColumnShown","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","isBackgroundBlurred","patternColor","messageSendKeyCombo","shouldSuggestStickers","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","parse","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","history","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","hasCustomBackground","customBackground","isCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCodeAsync","AuthCode","useModuleLoader","AuthPasswordAsync","AuthPassword","AuthRegisterAsync","AuthRegister","AuthQrCodeAsync","AuthQrCode","MainAsync","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAeC,KAAKP,EAAaH,KACpDa,EAAQb,GAAYG,EAAYH,IAKlC,IAFGc,GAAqBA,EAAoBf,GAEtCM,EAASC,QACdD,EAASU,OAATV,GAOF,IAAIW,EAAmB,GAGnBC,EAAqB,CACxBC,EAAG,GAMAP,EAAkB,CACrBO,EAAG,GAWJ,SAASC,EAAoBnB,GAG5B,GAAGgB,EAAiBhB,GACnB,OAAOgB,EAAiBhB,GAAUoB,QAGnC,IAAIC,EAASL,EAAiBhB,GAAY,CACzCI,EAAGJ,EACHsB,GAAG,EACHF,QAAS,IAUV,OANAP,EAAQb,GAAUU,KAAKW,EAAOD,QAASC,EAAQA,EAAOD,QAASD,GAG/DE,EAAOC,GAAI,EAGJD,EAAOD,QAKfD,EAAoBI,EAAI,SAAuBtB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,EACF,OAAO,kBAAC,GAAD,MAGT,GAAItJ,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,kBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAOoJ,KAIb,OAAOhK,EAA0BgK,KAAe,kBAAC,GAAD,Q,MCzC9Cv4D,KAEF7C,QAAQkD,IAAI,YAGd0K,cAAc+jD,OAEV9uD,KAEF7C,QAAQkD,IAAI,4BAGds4D,IAAS/N,OACP,kBAAC,GAAD,MACA3xD,SAASu8D,eAAe,SAGtBx1D,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAAS8K,iBAAiB,WAAY,KAEpC5G,QAAQkD,IAAI,eAAgByK","file":"main.c7769ee2bb8655152f13.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t1: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t1: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"6531d7c910f326b2774d\",\"2\":\"28b104a90f1c1a985b2b\",\"3\":\"4cc830a94ce5c77c6a75\",\"4\":\"dbb569ca042ea30048a3\",\"5\":\"c56542877a49a29d9fbe\",\"6\":\"6418278736080b7f34a0\",\"7\":\"b3047ce293a0e552bf8b\",\"8\":\"3a39c82251f73bbe0fea\",\"9\":\"a144f84357fa2a4cccc2\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"2\":1,\"3\":1,\"4\":1,\"5\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"6531d7c910f326b2774d\",\"2\":\"28b104a90f1c1a985b2b\",\"3\":\"4cc830a94ce5c77c6a75\",\"4\":\"dbb569ca042ea30048a3\",\"5\":\"c56542877a49a29d9fbe\",\"6\":\"6418278736080b7f34a0\",\"7\":\"b3047ce293a0e552bf8b\",\"8\":\"3a39c82251f73bbe0fea\",\"9\":\"a144f84357fa2a4cccc2\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\n \t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n \t\t\t// a Promise means \"currently loading\".\n \t\t\tif(installedChunkData) {\n \t\t\t\tpromises.push(installedChunkData[2]);\n \t\t\t} else {\n \t\t\t\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 90);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n scheduleNextState?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\n/* eslint-disable no-null/no-null */\nfunction helpGc(componentInstance: ComponentInstance) {\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n}\n\n/* eslint-enable no-null/no-null */\n\nfunction applyNextState(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.scheduleNextState || !componentInstance.forceUpdate) {\n componentInstance.scheduleNextState = throttleWithPrimaryRaf(() => applyNextState(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n }\n\n componentInstance.scheduleNextState();\n componentInstance.forceUpdate();\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\nexport function setGlobal(newGlobal?: GlobalState) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n runCallbacksThrottled();\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload) => {\n onDispatch(name, payload);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nfunction getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['LENGTH'];\n }\n\n return currentKeys.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { ApiDocument } from './messages';\n\nexport * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\n\nexport interface ApiOnProgress {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface ApiAttachment {\n blobUrl: string;\n filename: string;\n mimeType: string;\n size: number;\n quick?: {\n width: number;\n height: number;\n duration?: number;\n };\n voice?: {\n duration: number;\n waveform: number[];\n };\n previewBlobUrl?: string;\n}\n\nexport interface ApiWallpaper {\n slug: string;\n document: ApiDocument;\n}\n\nexport interface ApiSession {\n hash: string;\n isCurrent: boolean;\n isOfficialApp: boolean;\n isPasswordPending: boolean;\n deviceModel: string;\n platform: string;\n systemVersion: string;\n appName: string;\n appVersion: string;\n dateCreated: number;\n dateActive: number;\n ip: string;\n country: string;\n region: string;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Album';\n }\n\n if (photo) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Photo';\n }\n\n if (video) {\n if (video.isGif) {\n if (text) {\n return `${noEmoji ? '' : 'GIF '}${text.text}`;\n }\n\n return 'GIF';\n } else {\n if (text) {\n return `${noEmoji ? '' : '📹 '}${text.text}`;\n }\n\n return 'Video';\n }\n }\n\n if (sticker) {\n return `Sticker ${sticker.emoji}`;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n if (caption) {\n return `🎧 ${caption}`;\n }\n\n return 'Audio';\n }\n\n if (voice) {\n if (text) {\n return `${noEmoji ? '' : '🎤 '}${text.text}`;\n }\n\n return 'Voice Message';\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return 'Contact';\n }\n\n if (poll) {\n return `📊 ${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType,\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (chat && chat.unreadCount && !chat.isMuted) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n emoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return threadInfo.lastMessageId\n ? Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId)\n : threadInfo.lastReadInboxMessageId;\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n\n if (outlyingIds) {\n const found = outlyingIds.find((id) => {\n return !lastReadId || (id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled));\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = listedIds.find((id) => {\n return !lastReadId || (id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled));\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n} from '../config';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'Mac OS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\n\nexport const DPR = window.devicePixelRatio || 1;\n\n// `mask-image` CSS property for custom background slows down the scroll performance significantly\nexport const MASK_IMAGE_ENABLED = IS_IOS;\n\nlet isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler = typeof requestAnimationFrame | typeof onTickEnd | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n requestAnimationFrame(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafCallbacks.unshift(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n return fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, sessionId = '') {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionId],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n document.documentElement.lang = langCode;\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nexport function getTranslation(key: string, value?: any, format?: 'i') {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 09.05.2020\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\u2624|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","import {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport interface ISettings extends Record {\n messageTextSize: number;\n customBackground?: string;\n patternColor?: string;\n isBackgroundBlurred?: boolean;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n theme: 'light' | 'dark';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n languages?: ApiLanguage[];\n language: 'en' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'es' | 'uk';\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import {\n DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY, GRAMJS_SESSION_ID_KEY,\n} from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache or the session and refresh the page.\n if (Date.now() - startedAt <= STARTUP_TIMEOUT) {\n if (localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n } else if (localStorage.getItem(GRAMJS_SESSION_ID_KEY)) {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n } else {\n return;\n }\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(user: ApiUser, lang: LangFn) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return 'bot';\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { getTranslation } from '../../util/langProvider';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return getTranslation('SavedMessages');\n }\n return chat.title || getTranslation('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.lastMessage ? chat.lastMessage.date : 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id], folder, usersById, excludedChatIds, includedChatIds, pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (chat.isMuted && folder.excludeMuted) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!chat.isMuted && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n lang: LangFn,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(chatsById, usersById, folder, chatIdsCache);\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return 'You';\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n return currentKeys.every((prop) => currentProps[prop] === newProps[prop]);\n}\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasAsyncOpenClassName, setHasAsyncOpenClassName] = useState(false);\n\n if (isOpen) {\n setIsClosed(false);\n setHasAsyncOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasAsyncOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const hasOpenClassName = hasAsyncOpenClassName || (isOpen && noOpenTransition);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n hasOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { getTranslation } from './langProvider';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return getTranslation(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n getTranslation(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(date, format);\n}\n\nexport function formatFullDate(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = getTranslation('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatMonthAndYear(date: Date, isShort = false) {\n const format = getTranslation(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatHumanDate(datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(getTranslation('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(getTranslation('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(getTranslation(`Weekday.Short${weekDay}`))\n : upperFirst(getTranslation(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = getTranslation(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(date, format));\n}\n\nfunction formatDate(date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', getTranslation(MONTHS_FULL[monthIndex]))\n .replace('MMMM', getTranslation(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', getTranslation(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import { callApi } from '../api/gramjs';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({ endpoint: data.endpoint, keys: data.keys });\n}\n\nfunction checkIfSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function unsubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribeFromPush() {\n if (!checkIfSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribe(subscription);\n}\n\nexport async function subscribeToPush() {\n if (!checkIfSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribe(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch().setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Permission for Notifications was denied');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n }\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default RippleEffect;\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n ,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ISettings } from '../../types';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, isShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: isShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasGroupMessagePreview: isShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: isShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n\n useEffect(() => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: () => void,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n }, [isOpen]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter();\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [focusedIndex, elementRef, onSelectWithEnter]);\n\n return handleKeyDown;\n};\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","import { throttle } from './schedulers';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nlet windowSize = updateSizes();\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport default {\n get: () => windowSize,\n};\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n openTelegramLink,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [openTelegramLink, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {children || text}\n \n );\n};\n\nfunction getHref(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `http://${url}`;\n}\n\nfunction getDecodedUrl(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = getHref(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openTelegramLink']),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n
\n );\n};\n\nexport default DropdownMenu;\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-')) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-')) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('disable-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('disable-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1])) {\n category.emojis.push(emojiRaw[1]);\n emojiData.emojis[emojiRaw[1]] = {\n id: emojiRaw[1],\n colons: `:${emojiRaw[1]}:`,\n native: unifiedToNative(emojiRaw[0]),\n image: emojiRaw[0].toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0cfac43ee01937a2bf09.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n GRAMJS_SESSION_ID_KEY,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { unsubscribeFromPush } from '../../../util/pushNotifications';\nimport * as cacheApi from '../../../util/cacheApi';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n const sessionId = localStorage.getItem(GRAMJS_SESSION_ID_KEY) || undefined;\n\n void initApi(actions.apiUpdate, sessionId);\n\n return {\n ...global,\n authIsSessionRemembered: Boolean(sessionId),\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionId } = payload!;\n localStorage.setItem(GRAMJS_SESSION_ID_KEY, sessionId);\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribeFromPush();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n\n cacheApi.clear(MEDIA_CACHE_NAME);\n cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n cacheApi.clear(LANG_CACHE_NAME);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateCurrentUser,\n} from '../../../api/types';\nimport { DEBUG } from '../../../config';\nimport { subscribeToPush } from '../../../util/pushNotifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribeToPush();\n setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n const { sessionId } = update;\n if (sessionId && global.authRememberMe) {\n getDispatch().saveSession({ sessionId });\n }\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n}\n","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] New action from service worker', action);\n }\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n}\n","import { GlobalState } from './types';\n\nimport { ANIMATION_LEVEL_DEFAULT, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR } from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n isBackgroundBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n privacy: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n GRAMJS_SESSION_ID_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasActiveSession = localStorage.getItem(GRAMJS_SESSION_ID_KEY);\n if (hasActiveSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults for new settings which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authIsSessionRemembered',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'push',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey } = global.settings;\n\n return {\n byKey,\n privacy: {},\n };\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n isCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n isCustomBackgroundColor,\n isRightColumnShown,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n preloadTasks[page](),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n
\n {children}\n {shouldRenderMask && (\n
\n {page === 'main' ? (\n <>\n
\n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n return {\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(global.settings.byKey.customBackground),\n isCustomBackgroundColor: Boolean((global.settings.byKey.customBackground || '').match(/^#[a-f\\d]{6,8}$/i)),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 10;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n parseFullNumber(value);\n }, [authError, clearAuthError, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Sign in to Telegram

\n

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

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

Such error, many tabs

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

= (props: P) => any;\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n scheduleNextState?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\n/* eslint-disable no-null/no-null */\nfunction helpGc(componentInstance: ComponentInstance) {\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n}\n\n/* eslint-enable no-null/no-null */\n\nfunction applyNextState(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.scheduleNextState || !componentInstance.forceUpdate) {\n componentInstance.scheduleNextState = throttleWithPrimaryRaf(() => applyNextState(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n }\n\n componentInstance.scheduleNextState();\n componentInstance.forceUpdate();\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const GRAMJS_SESSION_ID_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 25;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\nexport function setGlobal(newGlobal?: GlobalState) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n runCallbacksThrottled();\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload) => {\n onDispatch(name, payload);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nfunction getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['LENGTH'];\n }\n\n return currentKeys.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { ApiDocument } from './messages';\n\nexport * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\n\nexport interface ApiOnProgress {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface ApiAttachment {\n blobUrl: string;\n filename: string;\n mimeType: string;\n size: number;\n quick?: {\n width: number;\n height: number;\n duration?: number;\n };\n voice?: {\n duration: number;\n waveform: number[];\n };\n previewBlobUrl?: string;\n}\n\nexport interface ApiWallpaper {\n slug: string;\n document: ApiDocument;\n}\n\nexport interface ApiSession {\n hash: string;\n isCurrent: boolean;\n isOfficialApp: boolean;\n isPasswordPending: boolean;\n deviceModel: string;\n platform: string;\n systemVersion: string;\n appName: string;\n appVersion: string;\n dateCreated: number;\n dateActive: number;\n ip: string;\n country: string;\n region: string;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Album';\n }\n\n if (photo) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Photo';\n }\n\n if (video) {\n if (video.isGif) {\n if (text) {\n return `${noEmoji ? '' : 'GIF '}${text.text}`;\n }\n\n return 'GIF';\n } else {\n if (text) {\n return `${noEmoji ? '' : '📹 '}${text.text}`;\n }\n\n return 'Video';\n }\n }\n\n if (sticker) {\n return `Sticker ${sticker.emoji}`;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n if (caption) {\n return `🎧 ${caption}`;\n }\n\n return 'Audio';\n }\n\n if (voice) {\n if (text) {\n return `${noEmoji ? '' : '🎤 '}${text.text}`;\n }\n\n return 'Voice Message';\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return 'Contact';\n }\n\n if (poll) {\n return `📊 ${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType,\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (chat && chat.unreadCount && !chat.isMuted) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n emoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return threadInfo.lastMessageId\n ? Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId)\n : threadInfo.lastReadInboxMessageId;\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n\n if (outlyingIds) {\n const found = outlyingIds.find((id) => {\n return !lastReadId || (id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled));\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = listedIds.find((id) => {\n return !lastReadId || (id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled));\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n} from '../config';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'Mac OS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\n\nexport const DPR = window.devicePixelRatio || 1;\n\n// `mask-image` CSS property for custom background slows down the scroll performance significantly\nexport const MASK_IMAGE_ENABLED = IS_IOS;\n\nlet isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler = typeof requestAnimationFrame | typeof onTickEnd | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n requestAnimationFrame(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafCallbacks.unshift(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n return fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, sessionId = '') {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionId],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n document.documentElement.lang = langCode;\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nexport function getTranslation(key: string, value?: any, format?: 'i') {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 09.05.2020\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\u2624|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","import {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport interface ISettings extends Record {\n messageTextSize: number;\n customBackground?: string;\n patternColor?: string;\n isBackgroundBlurred?: boolean;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n theme: 'light' | 'dark';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n languages?: ApiLanguage[];\n language: 'en' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'es' | 'uk';\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import {\n DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY, GRAMJS_SESSION_ID_KEY,\n} from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache or the session and refresh the page.\n if (Date.now() - startedAt <= STARTUP_TIMEOUT) {\n if (localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n } else if (localStorage.getItem(GRAMJS_SESSION_ID_KEY)) {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n } else {\n return;\n }\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(user: ApiUser, lang: LangFn) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return 'bot';\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { getTranslation } from '../../util/langProvider';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return getTranslation('SavedMessages');\n }\n return chat.title || getTranslation('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.lastMessage ? chat.lastMessage.date : 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id], folder, usersById, excludedChatIds, includedChatIds, pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (chat.isMuted && folder.excludeMuted) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!chat.isMuted && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n lang: LangFn,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(chatsById, usersById, folder, chatIdsCache);\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return 'You';\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n return currentKeys.every((prop) => currentProps[prop] === newProps[prop]);\n}\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasAsyncOpenClassName, setHasAsyncOpenClassName] = useState(false);\n\n if (isOpen) {\n setIsClosed(false);\n setHasAsyncOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasAsyncOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const hasOpenClassName = hasAsyncOpenClassName || (isOpen && noOpenTransition);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n hasOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { getTranslation } from './langProvider';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return getTranslation(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n getTranslation(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(date, format);\n}\n\nexport function formatFullDate(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = getTranslation('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatMonthAndYear(date: Date, isShort = false) {\n const format = getTranslation(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatHumanDate(datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(getTranslation('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(getTranslation('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(getTranslation(`Weekday.Short${weekDay}`))\n : upperFirst(getTranslation(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = getTranslation(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(date, format));\n}\n\nfunction formatDate(date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', getTranslation(MONTHS_FULL[monthIndex]))\n .replace('MMMM', getTranslation(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', getTranslation(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import { callApi } from '../api/gramjs';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({ endpoint: data.endpoint, keys: data.keys });\n}\n\nfunction checkIfSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function unsubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribeFromPush() {\n if (!checkIfSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribe(subscription);\n}\n\nexport async function subscribeToPush() {\n if (!checkIfSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribe(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch().setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Permission for Notifications was denied');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n }\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default RippleEffect;\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n ,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ISettings } from '../../types';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, isShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: isShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasGroupMessagePreview: isShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: isShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n\n useEffect(() => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: () => void,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n }, [isOpen]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter();\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [focusedIndex, elementRef, onSelectWithEnter]);\n\n return handleKeyDown;\n};\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","import { throttle } from './schedulers';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nlet windowSize = updateSizes();\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport default {\n get: () => windowSize,\n};\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n openTelegramLink,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [openTelegramLink, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {children || text}\n \n );\n};\n\nfunction getHref(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `http://${url}`;\n}\n\nfunction getDecodedUrl(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = getHref(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openTelegramLink']),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n
\n );\n};\n\nexport default DropdownMenu;\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-')) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-')) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('disable-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('disable-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1])) {\n category.emojis.push(emojiRaw[1]);\n emojiData.emojis[emojiRaw[1]] = {\n id: emojiRaw[1],\n colons: `:${emojiRaw[1]}:`,\n native: unifiedToNative(emojiRaw[0]),\n image: emojiRaw[0].toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"e1066b23c5448d0199e4.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n GRAMJS_SESSION_ID_KEY,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { unsubscribeFromPush } from '../../../util/pushNotifications';\nimport * as cacheApi from '../../../util/cacheApi';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n const sessionId = localStorage.getItem(GRAMJS_SESSION_ID_KEY) || undefined;\n\n void initApi(actions.apiUpdate, sessionId);\n\n return {\n ...global,\n authIsSessionRemembered: Boolean(sessionId),\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionId } = payload!;\n localStorage.setItem(GRAMJS_SESSION_ID_KEY, sessionId);\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribeFromPush();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n\n cacheApi.clear(MEDIA_CACHE_NAME);\n cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n cacheApi.clear(LANG_CACHE_NAME);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateCurrentUser,\n} from '../../../api/types';\nimport { DEBUG } from '../../../config';\nimport { subscribeToPush } from '../../../util/pushNotifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribeToPush();\n setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n const { sessionId } = update;\n if (sessionId && global.authRememberMe) {\n getDispatch().saveSession({ sessionId });\n }\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n}\n","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] New action from service worker', action);\n }\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n}\n","import { GlobalState } from './types';\n\nimport { ANIMATION_LEVEL_DEFAULT, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR } from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n isBackgroundBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n privacy: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n GRAMJS_SESSION_ID_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasActiveSession = localStorage.getItem(GRAMJS_SESSION_ID_KEY);\n if (hasActiveSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults for new settings which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authIsSessionRemembered',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'push',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey } = global.settings;\n\n return {\n byKey,\n privacy: {},\n };\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n isCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n isCustomBackgroundColor,\n isRightColumnShown,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n preloadTasks[page](),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n
\n {children}\n {shouldRenderMask && (\n
\n {page === 'main' ? (\n <>\n
\n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n return {\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(global.settings.byKey.customBackground),\n isCustomBackgroundColor: Boolean((global.settings.byKey.customBackground || '').match(/^#[a-f\\d]{6,8}$/i)),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 10;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n parseFullNumber(value);\n }, [authError, clearAuthError, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Sign in to Telegram

\n

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

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

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, authIsSessionRemembered, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n return authIsSessionRemembered ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState', 'authIsSessionRemembered']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/report.html b/dist/report.html index 616e267d..75e3e7fc 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [6 May 2021 at 05:11] + telegram-t [6 May 2021 at 19:32] diff --git a/dist/serviceWorker.js b/dist/serviceWorker.js index 2d1cc396..dd0724b5 100644 --- a/dist/serviceWorker.js +++ b/dist/serviceWorker.js @@ -1,2 +1,2 @@ -!function(e){var t={};function n(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(s,r,function(t){return e[t]}.bind(null,r));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";n.r(t);new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight;const s=new Map;async function r(e){const{url:t}=e.request,n=e.request.headers.get("range"),r=/^bytes=(\d+)-(\d+)?$/g.exec(n||""),a=Number(r[1]),i=Number(r[2]);let o=i;if((!o||o-a+1>524288)&&(o=a+524288-1),0===a&&1===o){const t=e.request.url.match(/fileSize=(\d+)&mimeType=([\w/]+)/),n=t&&Number(t[1]),s=t&&t[2];if(n&&s)return new Response(new Uint8Array(2).buffer,{status:206,statusText:"Partial Content",headers:[["Content-Range","bytes 0-1/"+n],["Accept-Ranges","bytes"],["Content-Length","2"],["Content-Type",s]]})}const c=`${t}?start=${a}&end=${o}`,[u,l]=await async function(e){const t=await self.caches.open("tt-media-progressive");return Promise.all([t.match(e+"&type=arrayBuffer").then(e=>e?e.arrayBuffer():void 0),t.match(e+"&type=headers").then(e=>e?e.json():void 0)])}(c);if(u)return new Response(u,{status:206,statusText:"Partial Content",headers:l});let f;try{f=await async function(e,t){if(!e.clientId)return;const n=await self.clients.get(e.clientId);if(!n)return;const r=(e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t})(s),a={},i=Promise.race([(o=3e4,new Promise(e=>{setTimeout(()=>e(),o)})).then(()=>Promise.reject(new Error("ERROR_PART_TIMEOUT"))),new Promise((e,t)=>{Object.assign(a,{resolve:e,reject:t})})]);var o;return s.set(r,a),i.catch(()=>{}).finally(()=>{s.delete(r)}),n.postMessage({type:"requestPart",messageId:r,params:t}),i}(e,{url:t,start:a,end:o})}catch(e){0}if(!f)return new Response("",{status:500,statusText:"Failed to fetch progressive part"});const{arrayBuffer:d,fullSize:p,mimeType:m}=f,g=Math.min(o-a+1,d.byteLength);o=a+g-1;const h=d.slice(0,g),y=[["Content-Range",`bytes ${a}-${o}/${p}`],["Accept-Ranges","bytes"],["Content-Length",String(g)],["Content-Type",m]];return g<=524288&&o<2097151&&async function(e,t,n){const s=await self.caches.open("tt-media-progressive");Promise.all([s.put(new Request(e+"&type=arrayBuffer"),new Response(t)),s.put(new Request(e+"&type=headers"),new Response(JSON.stringify(n)))])}(c,h,y),new Response(h,{status:206,statusText:"Partial Content",headers:y})}self.addEventListener("message",e=>{const{type:t,messageId:n,result:r}=e.data;if("partResponse"===t){const e=s.get(n);e&&e.resolve(r)}});const a={};function i(e,t){const n=function(e){return e.custom.from_id?parseInt(e.custom.from_id,10):e.custom.chat_id?-1*parseInt(e.custom.chat_id,10):e.custom.channel_id?-1*parseInt(e.custom.channel_id,10):void 0}(t),s=function(e){if(e.custom.msg_id)return parseInt(e.custom.msg_id,10)}(t);n&&e.postMessage({type:"focusMessage",payload:{chatId:n,messageId:s}}),e.focus&&e.focus()}const o=/[0-9a-f]{20}.*\.(js|css|woff2?|svg|png|jpg|json|wasm)$/;self.addEventListener("install",e=>{e.waitUntil(self.skipWaiting())}),self.addEventListener("activate",e=>{e.waitUntil(self.caches.delete("tt-assets")),e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",e=>{e.respondWith((()=>{const{url:t}=e.request;return t.includes("/progressive/")?r(e):t.startsWith("http")&&t.match(o)?async function(e){const t=await self.caches.open("tt-assets"),n=await t.match(e.request);if(n)return n;const s=await fetch(e.request);return t.put(e.request,s.clone()),s}(e):fetch(e.request)})())}),self.addEventListener("push",(function(e){const t=function(e){try{return e.data.json()}catch(e){return void 0}}(e);if(!t)return;const n=t.title||"Telegram WebZ alpha a684b4f",s=t.description;e.waitUntil(self.registration.showNotification(n,{body:s,data:t,icon:"android-chrome-192x192.png"}))})),self.addEventListener("notificationclick",(function(e){e.notification.close();const{data:t}=e.notification;e.waitUntil((async()=>{const e=(await self.clients.matchAll({type:"window"})).filter(e=>e.url===self.registration.scope);if(e.forEach(e=>i(e,t)),!self.clients.openWindow||e.length>0)return;const n=await self.clients.openWindow("https://webz.telegram.org/");n&&(a[n.id]=t)})())})),self.addEventListener("message",(function(e){if(e.data&&"clientReady"===e.data.type){const t=e.source;a[t.id]&&(i(t,a[t.id]),delete a[t.id])}}))}]); +!function(e){var t={};function n(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(s,r,function(t){return e[t]}.bind(null,r));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";n.r(t);new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight;const s=new Map;async function r(e){const{url:t}=e.request,n=e.request.headers.get("range"),r=/^bytes=(\d+)-(\d+)?$/g.exec(n||""),a=Number(r[1]),i=Number(r[2]);let o=i;if((!o||o-a+1>524288)&&(o=a+524288-1),0===a&&1===o){const t=e.request.url.match(/fileSize=(\d+)&mimeType=([\w/]+)/),n=t&&Number(t[1]),s=t&&t[2];if(n&&s)return new Response(new Uint8Array(2).buffer,{status:206,statusText:"Partial Content",headers:[["Content-Range","bytes 0-1/"+n],["Accept-Ranges","bytes"],["Content-Length","2"],["Content-Type",s]]})}const c=`${t}?start=${a}&end=${o}`,[u,l]=await async function(e){const t=await self.caches.open("tt-media-progressive");return Promise.all([t.match(e+"&type=arrayBuffer").then(e=>e?e.arrayBuffer():void 0),t.match(e+"&type=headers").then(e=>e?e.json():void 0)])}(c);if(u)return new Response(u,{status:206,statusText:"Partial Content",headers:l});let f;try{f=await async function(e,t){if(!e.clientId)return;const n=await self.clients.get(e.clientId);if(!n)return;const r=(e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t})(s),a={},i=Promise.race([(o=3e4,new Promise(e=>{setTimeout(()=>e(),o)})).then(()=>Promise.reject(new Error("ERROR_PART_TIMEOUT"))),new Promise((e,t)=>{Object.assign(a,{resolve:e,reject:t})})]);var o;return s.set(r,a),i.catch(()=>{}).finally(()=>{s.delete(r)}),n.postMessage({type:"requestPart",messageId:r,params:t}),i}(e,{url:t,start:a,end:o})}catch(e){0}if(!f)return new Response("",{status:500,statusText:"Failed to fetch progressive part"});const{arrayBuffer:d,fullSize:p,mimeType:m}=f,g=Math.min(o-a+1,d.byteLength);o=a+g-1;const h=d.slice(0,g),y=[["Content-Range",`bytes ${a}-${o}/${p}`],["Accept-Ranges","bytes"],["Content-Length",String(g)],["Content-Type",m]];return g<=524288&&o<2097151&&async function(e,t,n){const s=await self.caches.open("tt-media-progressive");Promise.all([s.put(new Request(e+"&type=arrayBuffer"),new Response(t)),s.put(new Request(e+"&type=headers"),new Response(JSON.stringify(n)))])}(c,h,y),new Response(h,{status:206,statusText:"Partial Content",headers:y})}self.addEventListener("message",e=>{const{type:t,messageId:n,result:r}=e.data;if("partResponse"===t){const e=s.get(n);e&&e.resolve(r)}});const a={};function i(e,t){const n=function(e){return e.custom.from_id?parseInt(e.custom.from_id,10):e.custom.chat_id?-1*parseInt(e.custom.chat_id,10):e.custom.channel_id?-1*parseInt(e.custom.channel_id,10):void 0}(t),s=function(e){if(e.custom.msg_id)return parseInt(e.custom.msg_id,10)}(t);n&&e.postMessage({type:"focusMessage",payload:{chatId:n,messageId:s}}),e.focus&&e.focus()}const o=/[0-9a-f]{20}.*\.(js|css|woff2?|svg|png|jpg|json|wasm)$/;self.addEventListener("install",e=>{e.waitUntil(self.skipWaiting())}),self.addEventListener("activate",e=>{e.waitUntil(self.caches.delete("tt-assets")),e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",e=>{e.respondWith((()=>{const{url:t}=e.request;return t.includes("/progressive/")?r(e):t.startsWith("http")&&t.match(o)?async function(e){const t=await self.caches.open("tt-assets"),n=await t.match(e.request);if(n)return n;const s=await fetch(e.request);return t.put(e.request,s.clone()),s}(e):fetch(e.request)})())}),self.addEventListener("push",(function(e){const t=function(e){try{return e.data.json()}catch(e){return void 0}}(e);if(!t)return;const n=t.title||"Telegram WebZ alpha 8ae9802",s=t.description;e.waitUntil(self.registration.showNotification(n,{body:s,data:t,icon:"android-chrome-192x192.png"}))})),self.addEventListener("notificationclick",(function(e){e.notification.close();const{data:t}=e.notification;e.waitUntil((async()=>{const e=(await self.clients.matchAll({type:"window"})).filter(e=>e.url===self.registration.scope);if(e.forEach(e=>i(e,t)),!self.clients.openWindow||e.length>0)return;const n=await self.clients.openWindow("https://webz.telegram.org/");n&&(a[n.id]=t)})())})),self.addEventListener("message",(function(e){if(e.data&&"clientReady"===e.data.type){const t=e.source;a[t.id]&&(i(t,a[t.id]),delete a[t.id])}}))}]); //# sourceMappingURL=serviceWorker.js.map \ No newline at end of file